Kotlin Coroutines
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:
- Write two
suspendfunctions and run them concurrently insidecoroutineScopeusingasyncandawait. - Explain what happens to sibling coroutines if one
asyncchild throws an exception insidecoroutineScope. - Identify which dispatcher (
IO,Default, orMain) fits database queries versus JSON parsing.