kotlinx.coroutines is JetBrains’ first-party Kotlin library for coroutine builders and concurrency APIs. Its builders bridge blocking code with suspending functions, start side-effecting tasks, or compute values asynchronously. section 14.6
Listing 14.7 Using the async coroutine builder to start a new coroutine
suspend fun slowlyAddNumbers(a: Int, b: Int): Int {
log("Waiting a bit before calculating $a + $b")
delay(100.milliseconds * a)
return a + b
}
fun main() = runBlocking {
log("Starting the async computation")
val myFirstDeferred = async { slowlyAddNumbers(2, 2) } #1
val mySecondDeferred = async { slowlyAddNumbers(4, 4) } #1
log("Waiting for the deferred value to be available")
log("The first result: ${myFirstDeferred.await()}") #2
log("The second result: ${mySecondDeferred.await()}") #2
}
Two async calls begin independent computations before either result is awaited, showing concurrent work and Deferred results. section 14.6.3
Choose a builder according to the result and execution pattern:
- runBlocking bridges blocking code and suspending functions, returning the lambda’s calculated value. section 14.6 section 14.6.3
- launch starts a coroutine for side effects and returns a Job. section 14.6 section 14.6.3
- async starts asynchronous value computation and returns Deferred<T>, whose result can be obtained with await. section 14.6.3
Unlike languages where async and await are keywords, Kotlin exposes them as library functions. Sequential suspending calls do not require async; use it when independent tasks should run concurrently and produce results. section 14.6.3
