Sobes.tech
Junior — Middle

Kus salvestatakse olek, vahetades suspend-funktsioonide vahel Kotlinis?

sobes.tech AI

Vastus AI-lt

The state when transitioning between suspend functions in Kotlin is stored in a coroutine state, which the compiler transforms into a finite automaton. This internal mechanism stores all local variables and the resume point in a generated class.

Thus, when the 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 resuming, 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.