Sobes.tech
Junior — Middle

How is asynchrony implemented when using coroutines?

sobes.tech AI

Answer from AI

Asynchrony in coroutines is achieved by suspending and resuming execution without blocking threads. When a coroutine encounters an operation that might take time (e.g., a network request), it suspends (suspend), freeing the thread for other tasks. After the operation completes, the coroutine resumes from the same point.

This is implemented through the suspend function mechanism and a compiler that transforms coroutines into state machines. As a result, coroutines allow writing asynchronous code in a sequential style without explicit callbacks.

Example in Kotlin:

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

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