Sobes.tech
Junior — Middle

Where is the state saved when transitioning between suspend functions in Kotlin?

sobes.tech AI

Answer from AI

The state when transitioning between suspend functions in Kotlin is stored in the coroutine state, which the compiler transforms into a finite state machine. This is an internal mechanism where all local variables and the resumption point are stored in a generated state class.

Thus, when a coroutine is suspended and resumed, control and data are restored from this object, allowing execution to continue from where it was interrupted.

It roughly looks like this (simplified):

suspend fun example() {
    val a = 1
    suspendFunction() // here the coroutine can suspend
    println(a) // after resumption, the value of a is preserved
}

The compiler creates a class that stores the variable a and the position in the code to resume execution.