Kotlin Coroutines

Coroutines give Kotlin a clean way to write asynchronous code without callback nesting. They are common in Android and backend services.

Suspend functions

A suspend function can pause execution at a suspension point (such as a network call or delay) without blocking the underlying OS thread, then resume where it left off. Because suspension is compiled into a state machine, asynchronous code reads sequentially from top to bottom without nested callbacks:

import kotlinx.coroutines.delay

suspend fun loadUser(id: String): String {
    delay(100)               // suspends coroutine without blocking the thread
    return "User($id)"
}

Structured concurrency

Coroutines always run inside a CoroutineScope, which ties child tasks to a parent lifecycle. If a parent scope is cancelled (for example, a user closes a screen or an HTTP request times out) or a sibling fails, all child coroutines are cancelled automatically so background work never leaks:

import kotlinx.coroutines.*

suspend fun fetchDashboard(): Pair<String, String> = coroutineScope {
    // Launch two independent I/O calls concurrently within this scope
    val user = async { loadUser("42") }
    val stats = async { delay(120); "12 tasks" }
    user.await() to stats.await()
}

Async flow

Use Dispatchers.IO for blocking disk or network calls, Dispatchers.Default for CPU-bound work, and Dispatchers.Main for UI updates—never block a UI or default dispatcher thread with synchronous I/O. For streams of multiple asynchronous values over time, Kotlin provides cold Flow<T> pipelines with operators like map, filter, and catch.

Practice

Apply suspension and structured concurrency concepts to a small workflow:

  1. Write two suspend functions and run them concurrently inside coroutineScope using async and await.
  2. Explain what happens to sibling coroutines if one async child throws an exception inside coroutineScope.
  3. Identify which dispatcher (IO, Default, or Main) fits database queries versus JSON parsing.