Coroutines and Flow cheat sheet
Key ideas
suspendis a compiler modifier that adds aContinuationparameter and rewrites the body into a state machine; you only callresume()when wrapping a callback withsuspendCancellableCoroutine.launchreturns aJob(no value);asyncreturns aDeferred<T>whose.await()gives the result, making it the right tool for parallel calls you need to combine.withContext(Dispatchers.IO)switches the dispatcher for a block and returns the result to the caller's original context; it does not start a separate coroutine.StateFlowis conflated and skips values equal to the current one;SharedFlowhas no initial value and delivers every value, including duplicates, to all active collectors.viewModelScopeusesSupervisorJob() + Dispatchers.Main.immediateand is cancelled when the ViewModel is cleared;lifecycleScopeis cancelled atDESTROYED.- A cold flow is a blueprint: code inside
flow { }does not run until a terminal operator such ascollect,first, orlaunchInstarts it. CancellationExceptionsignals normal cancellation and must always be rethrown;runCatchingswallows it and breaks the cancellation contract.repeatOnLifecycle(STARTED)cancels the block atonStopand restarts atonStart; in Compose usecollectAsStateWithLifecycle()instead ofcollectAsState().supervisorScopeisolates children so one child failure does not cancel its siblings; use it for independent tasks.flatMapLatestcancels the previous inner flow when the upstream key changes;mapLatestcancels a stale expensive computation.
APIs at a glance
| API or term | Use it for |
|---|---|
suspend | compiler modifier that rewrites a function into a state machine with a Continuation parameter |
launch | start a fire-and-forget child coroutine; returns a Job you can join() or cancel() |
async | start a child coroutine that produces a value via Deferred<T>.await(); use for parallel calls to combine |
withContext | switch dispatcher for a block and return the result to the caller's context; standard way to change dispatchers |
coroutineScope / supervisorScope | coroutineScope cancels siblings on any child failure; supervisorScope isolates children so one failure does not stop the rest |
StateFlow / MutableStateFlow | conflated, always-has-value stream that skips equal values; use update { } for atomic read-modify-write |
SharedFlow / MutableSharedFlow | multi-cast stream that delivers every value including duplicates; use for events, not state |
flatMapLatest | cancel the previous inner flow when the upstream key changes; standard for search fields and user-id switches |
repeatOnLifecycle | suspend until DESTROYED; cancel the block below STARTED and restart at onStart; use in onViewCreated |
collectAsStateWithLifecycle | Compose collector that stops below STARTED; use it on Android instead of collectAsState, which keeps collecting in the background |
flowOn | move upstream operators to a given dispatcher; affects only operators above it, not the collector |
Channel + receiveAsFlow | buffer one-off events for a single collector; unlike SharedFlow it keeps events sent while nobody collects (Google still prefers events as state) |
Snippets
ViewModel with StateFlow and safe exception handling
data class User(val id: String, val name: String)
interface UserRepository { suspend fun fetchUser(id: String): User }
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 {
try {
_user.value = repo.fetchUser(id)
} catch (e: CancellationException) {
throw e
} catch (e: IOException) {
_error.value = "Could not load"
}
}
}
}Search flow with debounce, flatMapLatest, and stateIn
// Inside a ViewModel: query is a StateFlow<String>, repository.search(q) returns List<String>
val results: StateFlow<List<String>> = query
.map { it.trim() }
.debounce(300)
.distinctUntilChanged()
.flatMapLatest { q ->
if (q.length < 3) flowOf(emptyList())
else flow { emit(repository.search(q)) }
.catch { emit(emptyList()) }
}
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())Lifecycle-aware collection in a Fragment
// Inside a Fragment whose root view is a TextView and whose viewModel exposes uiState: StateFlow<String>
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val label = view as TextView
viewLifecycleOwner.lifecycleScope.launch {
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
launch { viewModel.uiState.collect { label.text = it } }
// launch { viewModel.otherFlow.collect { ... } } // one launch per flow
}
}
}Rules of thumb
- Prefer
viewModelScopeorlifecycleScopeoverGlobalScopeor a hand-madeCoroutineScope; they tie cancellation to a real lifecycle. - Never swallow
CancellationException; always rethrow it incatchblocks so the coroutine actually stops. - Prefer
update { }overvalue = value + 1for read-modify-write onStateFlow;updateretries withcompareAndSetand never loses an update. - Prefer
withContext(Dispatchers.IO)over a rawThreadorExecutor; the work then belongs to the calling coroutine'sJobhierarchy and is cancellable. - Never call
runBlockingon the main thread; it blocks the looper and produces the ANR you were trying to avoid. - Prefer
repeatOnLifecycle(STARTED)orcollectAsStateWithLifecycle()overlifecycleScope.launch { collect }so collection stops when the UI is not visible.
Gotchas
- Swallowing CancellationException with runCatching or a catch-all catch (e: Exception). The coroutine stays cancelled but your code keeps running, writing stale state, logging a fake error, or looping forever. Fix: catch specific exception types and rethrow
CancellationExceptionfirst. - Using value = value + 1 instead of update { it + 1 } on StateFlow. Two coroutines can read the same old value and both write
old + 1, so one increment is silently lost. Fix: useupdate { }, which retries withcompareAndSet. - Putting catch after flatMapLatest in a long-lived stream. The first upstream error completes the whole flow and the screen stops updating. Fix: put
catchinside the inner flow so one failed request does not end the stream. - Collecting two flows one after another in the same coroutine.
collecton aStateFlownever returns, so the secondcollectnever starts. Fix:launcheach collection in its own child coroutine insiderepeatOnLifecycle. - Treating MutableSharedFlow(replay = 1) as a drop-in for StateFlow. It has no initial value, does not skip equal values, and makes the emitter wait for a slow collector instead of dropping old values. Fix: use
MutableStateFlowfor state; model one-off events as state the UI acknowledges, or aChannelwith a single collector. - Passing SupervisorJob() to launch, e.g. scope.launch(SupervisorJob()) { ... }. It replaces the parent, so the coroutine is no longer a child of the scope and is not cancelled with it. Fix: let the scope assign the parent; use
supervisorScopefor isolation.
Quick interview answers
What is the difference between launch and async?
launch returns a Job and is for fire-and-forget work; it does not produce a value. async returns a Deferred<T> whose .await() gives the result, making it the right tool for parallel calls you need to combine with awaitAll.
Why must you always rethrow CancellationException?
CancellationException signals normal cancellation and is never reported as a crash. If you swallow it, the coroutine stays cancelled but your code keeps running, writing stale state or looping, so you must rethrow it.
What is the difference between StateFlow and SharedFlow?
StateFlow always holds a value, is conflated, and skips values equal to the current one by equals. SharedFlow has no initial value and delivers every value, including duplicates, to all active collectors.
Why use repeatOnLifecycle(STARTED) instead of lifecycleScope.launch { collect }?
lifecycleScope.launch keeps collecting while the app is in the background, wasting resources and keeping WhileSubscribed upstreams alive. repeatOnLifecycle(STARTED) cancels the block at onStop and restarts it at onStart, matching UI visibility.
What does flatMapLatest do and when should you use it?
flatMapLatest cancels the previous inner flow when the upstream key changes, so only the latest request is active. Use it for search fields, user-id switches, or any case where a new key makes the old result stale.
Why avoid GlobalScope in a ViewModel?
GlobalScope has no Job, so nothing cancels its coroutines when the ViewModel is cleared. The coroutine survives clearing and keeps the ViewModel and its captured objects reachable until it finishes.