Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Kotlin
Stage 5: Specialization

Part 14 / Topic 2 of 7

The coroutine builders: runBlocking, launch, async

A coroutine is a suspendable computation; a coroutine builder is a function that starts one. main() itself is an ordinary blocking function, so something has to bridge it into the coroutine world -- that's runBlocking: it blocks the calling thread until everything inside it finishes, and is normally only used at an entry point like main or a test.

Inside a coroutine, two builders start new coroutines:

  • launch starts a coroutine and returns a Job -- fire-and-forget, no result to read back.
  • async starts a coroutine and returns a Deferred<T> -- a "promise" you read later with .await().
val job = launch {
    delay(100)
    println("Notification sent (launch)")
}
println("launch returned immediately, job is still running: ${job.isActive}")
job.join()                          // wait for it to finish before moving on

async is where the real payoff shows up. Three sequential suspend calls take roughly the sum of their delays; three async calls started together and awaited afterward take roughly the longest one, because they run concurrently:

val sequentialTime = measureTimeMillis {
    val a = fetchEta("Swiggy")
    val b = fetchEta("Zomato")
    val c = fetchEta("Dunzo")
    println("Sequential: [$a, $b, $c]")
}
println("Sequential took ${sequentialTime}ms (varies, ~900ms)")

val parallelTime = measureTimeMillis {
    val a = async { fetchEta("Swiggy") }
    val b = async { fetchEta("Zomato") }
    val c = async { fetchEta("Dunzo") }
    println("Parallel: [${a.await()}, ${b.await()}, ${c.await()}]")
}
println("Parallel took ${parallelTime}ms (varies, ~300ms)")
launch returned immediately, job is still running: true
Notification sent (launch)
Sequential: [Swiggy: ETA 12 min, Zomato: ETA 12 min, Dunzo: ETA 12 min]
Sequential took 913ms (varies, ~900ms)
Parallel: [Swiggy: ETA 12 min, Zomato: ETA 12 min, Dunzo: ETA 12 min]
Parallel took 307ms (varies, ~300ms)

All three async blocks start the moment async { ... } runs -- .await() only reads the result, it doesn't start the work. That's why starting all three first, then awaiting, gives ~300ms instead of ~900ms: the three 300ms waits overlap instead of stacking up.

Full program: examples/02_coroutine_builders.kt.

Done here? The practice set for Part 14 — including the solutions — is on the part page.

Search the guide