Junior — Middle
How is the suspension of execution handled in suspend functions in Kotlin?
sobes.tech AI
Answer from AI
In Kotlin, suspend functions implement a mechanism for pausing and resuming execution without blocking the thread. When a suspend function calls another suspend function, it can "pause" at the call point, preserving its state.
The execution is resumed using a coroutine mechanism, which the compiler transforms suspend functions into state machines. When paused, the function saves its current context and returns control to the caller. When the result is ready, execution resumes from where it was paused.
Example:
suspend fun fetchData(): String {
delay(1000) // pauses execution for 1 second
return "Data"
}
// Call from a coroutine
launch {
val result = fetchData() // execution pauses at delay
println(result) // after resuming
}
Thus, suspend functions allow writing asynchronous code that resembles synchronous code without blocking threads.