Junior — Middle
How is the suspension of coroutine execution implemented in programming?
sobes.tech AI
Answer from AI
Suspension of a coroutine in programming occurs using the suspend keyword (for example, in Kotlin) or similar mechanisms in other languages. This allows the coroutine to temporarily yield control without blocking the thread and to resume later.
Example in Kotlin:
suspend fun fetchData() {
val data = networkRequest() // suspension here until the response arrives
println(data)
}
In this example, networkRequest() is a suspend function that pauses the coroutine until the result is received, allowing other tasks to execute in the meantime. The thread is not blocked, and the coroutine automatically resumes after the operation completes.