Coroutines: Suspending Functions

Quick save... Quick load

Gaming Image

Coroutines utilise the idea of so-called continuations. In some computer games, "Quick Saves" are a tool for the player to take a snapshot of the entire game's state so that they can come back to it. Enough information is stored so that everything from projectiles, enemies and such can be perfectly recreated and continue to the next frame without missing a beat.

Continuations are like quick saves for a running program.

Imagine you could save all the info you need of the program so you can immediately pick up where you left off. This is what continuations do for the thread's code.

Suspended

In Kotlin, we can add the suspend keyword to a function to add this "quick-saving" feature to it. Under the hood, it saves/loads:

  • Current execution point
  • Local context (like the state of local variables)

Because these values are not very large (in number and size), we can keep track of many of these coroutines with not much extra memory or computer effort.