Thuta Learning
Kotlin
AdvancedProgrammingBeginner

Advanced Kotlin Coroutines

KotlinLesson 2445 min

What you'll walk away with

  • Explain what suspend means and why delay() waits without blocking a thread
  • Choose between runBlocking, launch, async, coroutineScope and withContext for a given job
  • Cancel work cooperatively, and rethrow CancellationException instead of swallowing it
  • Predict how a failing child affects its siblings in coroutineScope and supervisorScope
  • Pick Dispatchers.Default or Dispatchers.IO for CPU-bound and blocking work

Explain it simply

Coroutines in plain language

A coroutine is a piece of work that can pause and carry on later without holding a thread hostage while it waits. Think of a waiter in a busy restaurant. After taking your order he does not stand at the kitchen window until the food is ready; he serves other tables and returns when the bell rings. A suspend function is a stretch of the job where the waiter is allowed to walk away.

Kotlin supports this with one language keyword, suspend, and a library, kotlinx.coroutines, that provides launch, async, delay and dispatchers. The compiler rewrites each suspend function into a resumable state machine, so waiting costs a small object instead of a parked thread. That is why a program can run tens of thousands of coroutines where it could afford only a few hundred threads.

Problem → Why → Solution

The problem: waiting that holds a thread

A profile screen needs a user's name (120 ms away) and the number of orders (150 ms away). With ordinary blocking calls each wait parks a whole thread: the two calls run one after the other, the screen is ready after about 270 ms, and the thread did nothing useful for all of it. On a server that handles a thousand requests at once you would need a thousand parked threads; on Android the main thread would freeze and the app would stutter.

The usual escape routes create new problems. Starting raw threads or GlobalScope.launch makes the calls overlap, but nobody owns the work: nobody waits for it, nobody can cancel it when the user leaves the screen, and a failure inside it never reaches the code that started it.

BlockingProfile.kt
// Every call parks a whole thread while it waits.
fun loadName(id: Int): String {
    Thread.sleep(120)            // stands in for a network call
    return "user-$id"
}

fun loadOrderCount(id: Int): Int {
    Thread.sleep(150)
    return id * 3
}

fun main() {
    val name = loadName(1)            // 120 ms, thread blocked
    val orders = loadOrderCount(1)    // 150 ms more, thread blocked again
    println("$name has $orders orders")  // printed about 270 ms later
}

Waiting is not working

While the code waits for the network it is not computing anything, so it should not occupy a thread. Coroutines separate the two ideas: a suspended coroutine releases its thread for other work, and a scope keeps every launched coroutine tied to a parent that waits for it, cancels it and receives its failures. You get concurrency without losing track of who is responsible for what.

Core concept: suspend, builders and scopes

The suspend modifier declares that a function may pause in the middle. A suspend function can only be called from another suspend function or from a coroutine builder; calling it from an ordinary function is a compile error. delay(120) waits 120 ms, but unlike Thread.sleep it suspends the coroutine and frees the thread, and when the time is up a dispatcher resumes the coroutine.

Coroutine builders are the functions that start a coroutine; the table shows which one fits which job. The key difference is that launch returns a Job and no result value, while async returns a Deferred<T> whose result you collect with await().

BuilderReturnsUse it for
runBlockingthe lambda's resultmain() and tests; blocks the calling thread
launchJobwork inside a scope when no result is needed
asyncDeferred<T>concurrent work whose value you will await
coroutineScopethe lambda's resultgrouping child coroutines inside a suspend function
withContextthe lambda's resultswitching dispatcher for one block

Structured concurrency is the rule that every coroutine has a parent Job, and the parent waits until all of its children finish. Cancelling a parent cancels its children, and when one child fails the parent is cancelled too, which stops the siblings. That is why, once coroutineScope { ... } returns, you know everything inside it has finished or been stopped: nothing is left running behind your back. GlobalScope skips this rule, so it should be avoided in ordinary application code.

Cancellation is cooperative. cancel() does not stop a coroutine by force; it marks the job as cancelled, and the coroutine notices at its next suspension point, where a CancellationException is thrown. That exception is not an error but the normal 'stop now' signal, so if you catch it you must throw it again.

A scope is a tree of jobs
  1. A scope owns a root Job
  2. launch and async add child Jobs
  3. A parent waits for all children
  4. Cancellation flows down, failure up

A coroutine with no scope that waits for it (GlobalScope) will not be cancelled, awaited or heard from when it fails.

General pattern

kotlin
suspend fun task(arg: Type): Result {
    delay(millis)                      // any suspending call
    return value
}

suspend fun combined(): Combined = coroutineScope {
    val first = async { task(a) }      // starts right away
    val second = async { task(b) }     // runs alongside first
    Combined(first.await(), second.await())
}

Call suspending functions from a suspend function. To overlap work, start each async inside coroutineScope first and await afterwards, so the children run side by side instead of one after another.

Worked example: loading profiles concurrently

loadProfile starts two async children inside coroutineScope, so the name and the order count are fetched at the same time. main then asks for three profiles at once with awaitAll and prints everything from one place, which keeps the output in a fixed order even though the work overlaps.

Why runBlocking here?

main is an ordinary function, and ordinary functions cannot call suspend functions. runBlocking is the bridge: it blocks the calling thread until its coroutine finishes, which is right for main() and tests and wrong inside other coroutines. Kotlin also lets you declare suspend fun main() directly.

Profiles.kt
import kotlinx.coroutines.*

data class Profile(val name: String, val orders: Int)

suspend fun loadName(id: Int): String {
    delay(120)
    return "user-$id"
}

suspend fun loadOrderCount(id: Int): Int {
    delay(150)
    return id * 3
}

suspend fun loadProfile(id: Int): Profile = coroutineScope {
    val name = async { loadName(id) }
    val orders = async { loadOrderCount(id) }
    Profile(name.await(), orders.await())
}

fun main() = runBlocking {
    val profiles = (1..3).map { id -> async { loadProfile(id) } }.awaitAll()
    profiles.forEach { println(it) }
    println("total orders: ${profiles.sumOf { it.orders }}")
}

Code breakdown

  1. suspend and delaydelay(120)

    delay suspends the coroutine and releases the thread. A real network call behaves the same way: while it waits, the thread can serve other coroutines.

  2. Concurrent childrenval name = async { loadName(id) }

    async starts a child coroutine immediately and hands back a Deferred. The next line starts another one, so loadName and loadOrderCount overlap.

  3. Await the resultsProfile(name.await(), orders.await())

    await() suspends until the result is ready and then returns the value. Because the slower child takes 150 ms, the whole loadProfile takes about 150 ms, not 270 ms.

  4. Bridge from blocking codefun main() = runBlocking {

    runBlocking lets main enter the coroutine world. Code inside the block may call suspend functions, and main finishes only when the block does.

  5. Fan out, then gatherval profiles = (1..3).map { id -> async { loadProfile(id) } }.awaitAll()

    map starts all three async children first, and awaitAll waits for them and returns the results as a list in the order the children were started. That is why user-1, user-2, user-3 never swap places.

You should see
Profile(name=user-1, orders=3)
Profile(name=user-2, orders=6)
Profile(name=user-3, orders=9)
total orders: 18
What happens when loadProfile runs
  1. loadProfile starts two async children
  2. Both reach delay and suspend; the thread is free
  3. Timers fire; children resume and return values
  4. coroutineScope returns once both are done

Cancellation is cooperative

Cancelling a job does not stop its coroutine on the spot. Every suspending function in kotlinx.coroutines, such as delay, await and yield, checks for cancellation and throws a CancellationException. A loop that never suspends never notices, so long CPU-bound loops must call ensureActive() (or check isActive) themselves.

CooperativeCancel.kt
import kotlinx.coroutines.*

fun main() = runBlocking {
    val polite = mutableListOf<Int>()
    val stubborn = mutableListOf<Int>()

    val a = launch {
        for (i in 1..5) {
            ensureActive()
            polite += i
            if (i == 3) coroutineContext.job.cancel()
        }
    }
    val b = launch {
        for (i in 1..5) {
            stubborn += i
            if (i == 3) coroutineContext.job.cancel()
        }
    }
    joinAll(a, b)
    println("with ensureActive: $polite, cancelled=${a.isCancelled}")
    println("without any check: $stubborn, cancelled=${b.isCancelled}")
}

Both coroutines cancel themselves at item 3. The first calls ensureActive() on every pass and stops at [1, 2, 3]; the second never checks, so it finishes all five items although its job is already cancelled. The program prints with ensureActive: [1, 2, 3], cancelled=true and without any check: [1, 2, 3, 4, 5], cancelled=true.

Cleanup and timeouts

A cancelled coroutine unwinds through a CancellationException, so put cleanup in finally or in a catch block that rethrows. withTimeout cancels its block when the time runs out and throws TimeoutCancellationException; withTimeoutOrNull returns null instead of throwing.

CleanupAndTimeout.kt
import kotlinx.coroutines.*

fun main() = runBlocking {
    val worker = launch {
        try {
            println("worker: waiting")
            delay(10_000)
        } catch (e: CancellationException) {
            println("worker: cleaning up after ${e::class.simpleName}")
            throw e
        } finally {
            println("worker: finally runs")
        }
    }
    delay(50)
    worker.cancelAndJoin()
    println("worker cancelled: ${worker.isCancelled}")

    val fast = withTimeoutOrNull(100) { delay(20); "fast result" }
    val slow = withTimeoutOrNull(100) { delay(200); "slow result" }
    println("fast=$fast slow=$slow")

    try {
        withTimeout(60) { delay(200) }
    } catch (e: TimeoutCancellationException) {
        println("timeout: ${e.message}")
    }
}

The output is worker: waiting, worker: cleaning up after JobCancellationException, worker: finally runs, worker cancelled: true, fast=fast result slow=null and timeout: Timed out waiting for 60 ms, in that order. cancelAndJoin() waits for the worker's cleanup to finish, which is why the cleanup messages appear before the next println.

When a child fails

Inside coroutineScope the first failure cancels the other children, and coroutineScope itself rethrows the exception, so a try/catch around the scope catches it. supervisorScope changes the rule: children fail independently, and you handle each failure where you await it.

ChildFailure.kt
import kotlinx.coroutines.*

suspend fun download(id: Int): String {
    delay(40L * id)
    if (id == 2) throw IllegalStateException("file $id is corrupt")
    return "file-$id"
}

fun main() = runBlocking {
    val all = try {
        coroutineScope {
            (1..3).map { id -> async { download(id) } }.awaitAll()
        }
    } catch (e: IllegalStateException) {
        listOf("coroutineScope failed: ${e.message}")
    }
    println(all)

    val each = supervisorScope {
        (1..3).map { id -> async { download(id) } }.map { job ->
            try {
                job.await()
            } catch (e: IllegalStateException) {
                "failed (${e.message})"
            }
        }
    }
    println(each)
}

The first output is [coroutineScope failed: file 2 is corrupt]: file-3 was cancelled before it could finish, so it has no result. The second is [file-1, failed (file 2 is corrupt), file-3], because under supervisorScope the other two children complete normally.

Dispatchers: where the code runs

A dispatcher decides which thread, or thread pool, a coroutine runs on. Coroutines inside runBlocking run on the thread that called it, and withContext(Dispatchers.Default) sends one block to another pool and hands the result back. The table lists the dispatchers you will meet most.

DispatcherMeant forNotes
Dispatchers.DefaultCPU-bound work: sorting, parsing, image processingshared pool sized to the number of CPU cores
Dispatchers.IOblocking calls: files, JDBC, blocking HTTP clientsshares threads with Default and can grow to a larger pool
Dispatchers.Mainupdating the user interfaceexists only with a UI artifact (Android, Swing, JavaFX); a plain JVM throws IllegalStateException
Dispatchers.kt
import kotlinx.coroutines.*

fun main() = runBlocking {
    val log = mutableListOf<String>()
    println("main thread: ${Thread.currentThread().name}")

    val onDefault = withContext(Dispatchers.Default) {
        Thread.currentThread().name.startsWith("DefaultDispatcher-worker")
    }
    val onIo = withContext(Dispatchers.IO) {
        Thread.currentThread().name.startsWith("DefaultDispatcher-worker")
    }
    println("Default uses the shared pool: $onDefault, IO uses the shared pool: $onIo")
    println("back on: ${Thread.currentThread().name}")

    val blocking = launch { log += "A start"; Thread.sleep(60); log += "A end" }
    val other = launch { log += "B start"; log += "B end" }
    joinAll(blocking, other)
    println("Thread.sleep: $log")
    log.clear()

    val suspending = launch { log += "A start"; delay(60); log += "A end" }
    val other2 = launch { log += "B start"; log += "B end" }
    joinAll(suspending, other2)
    println("delay:        $log")
}

The first println shows main thread: main, and after withContext the coroutine is back on the main thread. The last two lines matter most: with Thread.sleep, A holds the only thread, so B can start only after A ends and the log is [A start, A end, B start, B end]. With delay, A suspends and frees the thread, so B finishes in the gap and the log is [A start, B start, B end, A end].

Adding the library to a project

The suspend keyword is part of the language, but launch, async, delay and the dispatchers live in the kotlinx.coroutines library, so every Gradle project adds it as a dependency. Check the official release page for the current version instead of copying a number from a tutorial. The test helper runTest comes from the separate kotlinx-coroutines-test artifact.

build.gradle.kts
dependencies {
    // replace <version> with the current kotlinx.coroutines release
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:<version>")
    testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:<version>")
}

In real projects

Where coroutines run in real projects

Coroutines are the standard way to write asynchronous code in Android and Kotlin server projects. The common shape in those projects is the same: a scope is tied to the lifetime of some unit of work, and suspend functions are called inside it.

  • Android: viewModelScope.launch and lifecycleScope cancel their work automatically when the screen or ViewModel goes away, so a network call that finishes after the user has left no longer touches the UI.
  • Servers such as Ktor and Spring WebFlux: each request is handled by a coroutine and handlers can be suspend functions, so while one waits for a database or another service the threads keep serving many other requests.
  • Fan-out with a timeout: calling three services at once with async, cutting off the slow one with withTimeoutOrNull and answering with a partial result is a very common design.
  • Tests: runTest from kotlinx-coroutines-test skips delays using virtual time, so code that waits for seconds can be tested in milliseconds.

Common mistakes

Common mistakes with coroutines

Calling a blocking function inside a coroutine

Thread.sleep, blocking JDBC calls or file reads do not suspend the coroutine; they hold the thread. When the pool runs out of threads, every other coroutine stalls. Use delay, or wrap the blocking code in withContext(Dispatchers.IO).

Reaching for GlobalScope.launch

GlobalScope has no parent job, so nobody waits for its work even when the program is ending. In the code below main prints 'main ends' and finishes, so the println("late") after delay(100) never appears. The compiler also warns 'this is a delicate API and its use requires care'. Use coroutineScope or a scope with your own lifecycle.

Swallowing CancellationException

catch (e: Exception) and runCatching also catch CancellationException. If you log it and carry on, the cancelled coroutine keeps running. In the code below 'still running after cancel' is printed even though the worker was cancelled. Catch a more specific exception, or rethrow CancellationException.

Awaiting an async immediately

async { work() }.await() starts the job and waits at once, which gives no concurrency and is the same as calling work() directly. Start every async first and await afterwards. If you only want to change dispatcher, use withContext, not async.

SwallowedCancel.kt
import kotlinx.coroutines.*

fun main() = runBlocking {
    val worker = launch {
        try {
            delay(1000)
        } catch (e: Exception) {
            println("swallowed ${e::class.simpleName}")
        }
        println("still running after cancel")
    }
    delay(30)
    worker.cancelAndJoin()
    println("worker cancelled: ${worker.isCancelled}")
}
GlobalScopeLeak.kt
import kotlinx.coroutines.*

fun main() {
    GlobalScope.launch {
        delay(100)
        println("late")      // never printed: main has already returned
    }
    println("main ends")
}

Best practices

Best practices

  • Make suspend functions main-safe: if there is blocking work, the function itself switches dispatcher with withContext instead of relying on the caller.
  • Keep concurrent work inside coroutineScope so that when the function returns, every child is guaranteed to be finished.
  • Accept a dispatcher as a constructor parameter instead of hardcoding it in the class, so tests can supply their own.
  • Use supervisorScope only when you deliberately want children to fail independently, and handle each failure where you await it.

Mini challenge

Mini challenge: a price board that cuts off slow sources

Write loadPrices, which fetches the prices for a list of symbols concurrently. Give each symbol at most 120 ms; if it takes longer its result must be null. fetchPrice is a fake network call whose latency depends on the symbol.

  • loadPrices starts one async per symbol inside coroutineScope
  • Cut each symbol off with withTimeoutOrNull(120) and return a Map<String, Int?>
  • Call it from main with BTC, ETH and DOGE and print the map
  • Use check() to confirm BTC has a price and DOGE is null
PriceBoard.kt
import kotlinx.coroutines.*

// Fake network call: the latency depends on the symbol.
suspend fun fetchPrice(symbol: String): Int {
    val (latencyMs, price) = when (symbol) {
        "BTC" -> 10L to 64_000
        "ETH" -> 40L to 3_200
        else -> 200L to 12
    }
    delay(latencyMs)
    return price
}

// TODO: start one async per symbol inside coroutineScope,
//       wrap each fetch in withTimeoutOrNull(120),
//       then await them all and build the map
suspend fun loadPrices(symbols: List<String>): Map<String, Int?> {
    TODO()
}

fun main() = runBlocking {
    // TODO: call loadPrices(listOf("BTC", "ETH", "DOGE")) and print the result
    // TODO: check() that BTC has a price and DOGE is null
}

Expected: It prints {BTC=64000, ETH=3200, DOGE=null}. DOGE's fetch needs 200 ms, so it is cancelled at 120 ms and becomes null, while the other two finish in time.

Show hint

First turn every symbol into a pair (symbol to async { ... }) with map, and only then await and build the map with associate. If you start one and await it immediately, the work will not overlap. withTimeoutOrNull already returns null when time runs out.

Show solution
PriceBoard.kt
import kotlinx.coroutines.*

// Fake network call: the latency depends on the symbol.
suspend fun fetchPrice(symbol: String): Int {
    val (latencyMs, price) = when (symbol) {
        "BTC" -> 10L to 64_000
        "ETH" -> 40L to 3_200
        else -> 200L to 12
    }
    delay(latencyMs)
    return price
}

suspend fun loadPrices(symbols: List<String>): Map<String, Int?> = coroutineScope {
    val pending = symbols.map { symbol ->
        symbol to async { withTimeoutOrNull(120) { fetchPrice(symbol) } }
    }
    pending.associate { (symbol, deferred) -> symbol to deferred.await() }
}

fun main() = runBlocking {
    val prices = loadPrices(listOf("BTC", "ETH", "DOGE"))
    println(prices)
    check(prices["BTC"] == 64_000)
    check(prices["DOGE"] == null)
    check(loadPrices(emptyList()).isEmpty())
}

Quick quiz 1 / 3

What does this print? fun main() = runBlocking { launch { delay(100); println("B") }; launch { println("A") }; println("C") }

Quick quiz 2 / 3

A coroutine wraps delay() in catch (e: Exception) { println(e) }. What is wrong with that?

Quick quiz 3 / 3

A coroutineScope holds three async children and the second throws. If the scope is wrapped in try/catch, what happens?

What to remember

  • A suspend function can pause without blocking a thread, and launch, async and runBlocking start coroutines.
  • In structured concurrency a parent waits for, cancels and receives failures from all its children; GlobalScope bypasses that.
  • Cancellation is cooperative, and CancellationException must be rethrown, never swallowed.
  • In coroutineScope a failing child cancels its siblings; in supervisorScope children fail independently.
  • Default is for CPU work and IO for blocking work, and withContext switches the dispatcher.

Coroutines Basics — Kotlin

Coroutines Basics — Kotlin

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Advanced Kotlin Coroutines | Thuta Learning