Introduction: Coroutines Under the Hood
Learn how coroutines and functions look under the hood.
We'll cover the following...
A certain kind of person cannot accept that a car can just be driven. They need to open the car's hood to understand how it works. This chapter is purely explanatory. It tries to explain to a satisfactory level how coroutines work. The key lessons are:
Suspending functions are like state machines, with a possible state at the beginning of the function and after each suspending function call.
The number identifying the state and the local data is kept in the continuation object.
Continuation of a function decorates a continuation of its caller function; as a result, all these continuations represent a call stack used when we resume or a resumed function completes.
If we want to learn some internals (simplified, of course), read on.
Continuation–passing style
We could have implemented suspending functions in a few ways, but the Kotlin team decided on an option called the continuation-passing style. This means that continuations (explained in the previous lessons) are passed from function to function as arguments. By convention, a continuation takes the last parameter position. Let's have a look. ...