Coroutines basics: suspend and builders
Why it matters
- Every async call in a modern Android app goes through a suspend function or a builder; picking the wrong one causes leaked coroutines, unhandled exceptions, or UI freezes.
- Interviewers at mid and senior levels ask you to explain the Continuation mechanism and the difference between launch and async without hand-waving.
- Builders define the Job hierarchy. Getting the hierarchy wrong means a cancelled screen keeps running network calls in the background.
- withContext is the standard way to switch dispatchers inside a suspend chain. Using GlobalScope or a raw Thread instead breaks structured concurrency.
The simple explanation
- A suspend function is like a chef who can pause mid-recipe, hand the plate to a waiter, and resume later without blocking the kitchen.
- launch is 'start a side task and forget the result' (fire-and-forget).
- async is 'start a side task and I will collect the result later' (a promise).
- coroutineScope is a kitchen shift: when the shift ends, every station must be closed before the chef leaves.
- supervisorScope is a kitchen where one station burning down does not shut the others.
- withContext is 'move this step to a different station (thread pool) and bring the result back.'
The suspend keyword is a compile-time contract. The Kotlin compiler adds a hidden Continuation parameter to every suspend fun and turns its body into a state machine. When the function actually suspends, it saves its local state and returns a special COROUTINE_SUSPENDED marker to its caller; later the Continuation is resumed and the function carries on from where it stopped. While it is suspended, no thread is blocked. suspend alone does not move work to a background thread: blocking code inside a suspend function still blocks whatever thread runs it.
launch and async are coroutine builders: they start a new coroutine in a CoroutineScope. coroutineScope, supervisorScope and withContext are suspend functions that run a block in a new scope and return its result.
| Function | Returns | Caller waits? | When a child fails |
|---|---|---|---|
launch | Job | No, returns at once | The failure cancels the parent and its other children (unless the parent uses a SupervisorJob) |
async | Deferred<T> | No, returns at once | Same as launch; await() also throws the exception |
coroutineScope | T (block result) | Yes, until the block and all its children finish | Cancels the other children and rethrows to the caller |
supervisorScope | T | Yes, until the block and all its children finish | Other children keep running; the failed child must handle its own error |
withContext | T | Yes, until the block and all its children finish | Cancels the other children and rethrows to the caller |
withContext is the one you use most: it runs its block with a changed CoroutineContext (usually a different dispatcher), suspends the caller until the block is done, and returns the result.
In Android, viewModelScope (on a ViewModel) and lifecycleScope (on a LifecycleOwner) give you a ready-made scope that is cancelled when the ViewModel is cleared or the lifecycle is destroyed. Launch from those scopes, not from GlobalScope.
Notes
suspendis a modifier, not a runtime call. The compiler adds aContinuationparameter and rewrites the body into a state machine. You only callresume()yourself when wrapping a callback API withsuspendCancellableCoroutine.- A suspend function can only be called from another suspend function or from inside a coroutine.
launchreturns aJob. You can calljob.join()orjob.cancel(). It does not give you a value.asyncreturns aDeferred<T>. Call.await()to get the value.await()is itself asuspendfunction.coroutineScopesuspends the caller until all child coroutines finish. If any child throws, the scope cancels the rest and rethrows.supervisorScopeisolates children: one child failing does not cancel its siblings. Use it when tasks are independent.withContext(Dispatchers.IO)switches the dispatcher for the block and returns the result to the original context. It is the standard way to change dispatchers inside a suspend chain.viewModelScopeusesSupervisorJob() + Dispatchers.Main.immediateand is cancelled when the ViewModel is cleared.lifecycleScopeis cancelled when theLifecyclereachesDESTROYED. In a Fragment, useviewLifecycleOwner.lifecycleScopefor work that touches views.Dispatchers.Main.immediateruns the code straight away if you are already on the main thread.Dispatchers.Mainalways posts it to the main looper first.- Avoid
GlobalScope. It has noJob, so nothing cancels its coroutines when a screen or ViewModel goes away. withTimeout(5_000) { ... }throwsTimeoutCancellationException, a subclass ofCancellationException. If it escapes alaunch, the coroutine simply ends as cancelled, with no crash and no log. Catch it where you need to react, or usewithTimeoutOrNull, which returnsnullinstead.
Code example
This ViewModel shows the standard pattern: a suspend repository call wrapped in withContext(Dispatchers.IO), launched from viewModelScope, and the result posted to a StateFlow.
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import java.io.IOException
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
data class User(val id: String, val name: String)
interface UserApi {
fun getUser(id: String): User // a blocking call
}
// Repository: the only place that touches the network or DB
class UserRepository(private val api: UserApi) {
// main-safe: callers can use it from the main thread
suspend fun fetchUser(id: String): User =
withContext(Dispatchers.IO) { // run the blocking call on the IO pool
api.getUser(id)
}
}
class UserViewModel(private val repo: UserRepository) : ViewModel() {
private val _user = MutableStateFlow<User?>(null)
val user: StateFlow<User?> = _user.asStateFlow()
private val _error = MutableStateFlow<String?>(null)
val error: StateFlow<String?> = _error.asStateFlow()
fun loadUser(id: String) {
viewModelScope.launch { // runs on Dispatchers.Main.immediate
try {
_user.value = repo.fetchUser(id)
} catch (e: CancellationException) {
throw e // never swallow cancellation
} catch (e: IOException) {
_error.value = "Could not load the user"
}
}
}
}withContext(Dispatchers.IO)is the dispatcher switch; the rest of the code inlaunchstays on the main thread, so writing to theStateFlowis safe.viewModelScope.launchcreates a childJobunder the ViewModel'sSupervisorJob, so it is cancelled when the ViewModel is cleared.- The
catchforCancellationExceptioncomes first and rethrows it. TheIOExceptionbranch then handles only real network errors.
Run the idea in plain Kotlin
launch returns at once, two async calls run at the same time, and coroutineScope waits for its child before returning.
import kotlinx.coroutines.*
suspend fun fetchName(): String {
delay(200)
return "Ada"
}
suspend fun fetchScore(): Int {
delay(300)
return 42
}
fun main() = runBlocking {
val start = System.currentTimeMillis()
val job = launch {
delay(100)
println("launch: side task done")
}
println("launch returned a Job immediately")
val name = async { fetchName() }
val score = async { fetchScore() }
println("async started two calls")
println("result: " + name.await() + " " + score.await())
val elapsed = System.currentTimeMillis() - start
println("ran in parallel: " + (elapsed < 450))
job.join()
val value = coroutineScope {
launch {
delay(50)
println("coroutineScope child finished")
}
"block value"
}
println("coroutineScope returned: " + value)
}Expected output:
launch returned a Job immediately
async started two calls
launch: side task done
result: Ada 42
ran in parallel: true
coroutineScope child finished
coroutineScope returned: block value
The two calls take 200 ms and 300 ms but finish together after about 300 ms, not 500 ms. coroutineScope returns its value only after its child has printed.
In production
- Crashlytics showed
IllegalStateException: Fragment not attached to a contextafter users left a screen during a slow load. - The Fragment called
GlobalScope.launch { val data = api.fetch(); render(data) }. The coroutine outlived the Fragment. - When the response arrived,
rendercalledrequireContext()on a detached Fragment and crashed.
- Moved the call into a
ViewModelwithviewModelScope.launch, exposed the result as aStateFlow, and so also kept the result across rotation. - The Fragment collects it with
viewLifecycleOwner.lifecycleScope.launchandrepeatOnLifecycle(Lifecycle.State.STARTED), so collection stops when the view is destroyed. - No coroutine started by the Fragment can outlive its view any more.
- Battery reports showed a CPU core busy at 100% after users left a live-scores screen.
- The loop was
while (true) { runCatching { scores.value = api.poll(); delay(5_000) } }inviewModelScope. - When the ViewModel was cleared,
delaythrewCancellationException,runCatchingcaught it, and the loop went round again. Every laterdelaythrew at once, so the loop spun without pausing.
- Replaced
runCatchingwithtry/catch (e: IOException)so cancellation is no longer caught. - Moved
delay(5_000)outside thetryand changed the loop towhile (isActive). - Added a unit test with
runTestthat cancels the scope and checks the fake API is not called again.
Common mistakes
- Creating your own scope and never cancelling it.
CoroutineScope(Dispatchers.IO).launch { ... }in a class has no owner, so nothing cancels it when the screen goes away. Launch from viewModelScope or lifecycleScope, or cancel your own scope when its owner ends. - Using async where launch is enough. If you never need the value,
asynconly adds aDeferredyou have to remember to await. Use async when you need results, typically to run calls in parallel and combine them withawaitorawaitAll. - Switching threads with a raw Thread or Executor. That work is outside the Job hierarchy, so cancellation never reaches it. Use withContext(Dispatchers.IO) so the work belongs to the calling coroutine.
- Swallowing CancellationException with runCatching or a catch-all. The coroutine stays cancelled, but your code carries on as if it were not: it writes state, logs a fake error, or loops. Catch specific exceptions, or rethrow CancellationException first.
- Using GlobalScope in a ViewModel. GlobalScope lives as long as the process. The coroutine survives ViewModel clearing and keeps the ViewModel reachable until it finishes. Use viewModelScope instead.
- Calling withContext(Dispatchers.Main) inside a ViewModel. viewModelScope already runs on Dispatchers.Main.immediate. Switching to Dispatchers.Main posts the block to the main looper for nothing. Switch away to IO or Default only for the work that needs it.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What does the suspend keyword actually do at compile time?”
“When do you use async instead of launch?”
“What is the difference between coroutineScope and supervisorScope?”
“Why must CancellationException be rethrown?”
Quiz
What does the Kotlin compiler add to every suspend function?
Which builder returns a Deferred<T>?
What happens to sibling coroutines in a coroutineScope when one child throws?
Why is runCatching around a suspend call risky?
0 of 4 answered
Mini task
15-minute exercise: convert a blocking call to a suspend + builder pattern
You have a legacy function in a ViewModel that calls a blocking Retrofit API on the main thread.
-
Open your project and find a
ViewModelthat calls a blocking repository method directly from a click handler. If you do not have one, create aFakeRepowith afun getUsers(): List<User>that callsThread.sleep(3_000)and returns a list. -
Change the repository method to
suspend fun getUsers(): List<User>and wrap the blocking call inwithContext(Dispatchers.IO) { ... }. -
In the
ViewModel, call the new suspend function fromviewModelScope.launch { ... }. Store the result in aMutableStateFlow<List<User>>and expose it as a read-onlyStateFlow. AddLog.d("Users", "updating state")just before you write the result. -
In a composable, collect the
StateFlowwithcollectAsStateWithLifecycle(). In a View-based screen,collectinsiderepeatOnLifecycle(Lifecycle.State.STARTED). Show the list. -
Start a load, then press Back to leave the screen before the 3 seconds are up, so the ViewModel is cleared. The sleep itself is not interrupted, but
withContextchecks for cancellation when its block returns and throwsCancellationException, so the log line never prints.
Done condition: the UI shows the list without freezing, the sleep runs on a background thread, and "updating state" does not appear when you leave the screen during a load.