Sobes.tech
Junior — Middle

How do coroutines implement asynchronous execution of operations?

sobes.tech AI

Answer from AI

Coroutines in Kotlin implement asynchronous execution of operations by suspending and resuming execution without blocking threads. When a suspending function is called, the coroutine saves its state and releases the thread, allowing other tasks to run. When the result of an asynchronous operation is ready, the coroutine resumes from where it was suspended.

This is achieved through a compilation mechanism that transforms coroutines into state machines. Thus, coroutines allow writing asynchronous code in a sequential style, simplifying reading and maintenance.

Example:

suspend fun fetchData(): String {
    delay(1000) // suspends the coroutine for 1 second without blocking the thread
    return "Data received"
}

fun main() = runBlocking {
    println("Start")
    val result = fetchData() // asynchronously wait for the result
    println(result)
    println("End")
}