liveBook · Manning

Kotlinx.coroutines

As explained in Kotlin in Action, 2E

kotlinx.coroutines is JetBrains' Kotlin library providing coroutine builders, synchronization primitives, and other concurrency APIs.

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

How Kotlin in Action, 2E covers it

How deep it goes
Defines three builders by purpose, demonstrates async and await, and notes dispatchers without detailing their implementation.
Examples
Uses two delayed async computations that return sums, then awaits both results.
What it assumes
Builds on suspending functions while clarifying that async and await are library functions rather than Kotlin keywords.
What you can do after
Apply it via kotlinx.coroutines to bridge blocking code, launch tasks, and await concurrent results.
How it connects
Connects coroutine builders with suspending functions, deferred values, await, dispatchers, and threads.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.