Coroutines and Flow cheat sheet

Revise Kotlin coroutines and Flow: suspend, launch, async, withContext, StateFlow, SharedFlow, flatMapLatest, and lifecycle-aware collection for Android.

Key ideas

  1. suspend is a compiler modifier that adds a Continuation parameter and rewrites the body into a state machine; you only call resume() when wrapping a callback with suspendCancellableCoroutine.
  2. launch returns a Job (no value); async returns a Deferred<T> whose .await() gives the result, making it the right tool for parallel calls you need to combine.
  3. 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.
  4. StateFlow is conflated and skips values equal to the current one; SharedFlow has no initial value and delivers every value, including duplicates, to all active collectors.
  5. viewModelScope uses SupervisorJob() + Dispatchers.Main.immediate and is cancelled when the ViewModel is cleared; lifecycleScope is cancelled at DESTROYED.
  6. A cold flow is a blueprint: code inside flow { } does not run until a terminal operator such as collect, first, or launchIn starts it.
  7. CancellationException signals normal cancellation and must always be rethrown; runCatching swallows it and breaks the cancellation contract.
  8. repeatOnLifecycle(STARTED) cancels the block at onStop and restarts at onStart; in Compose use collectAsStateWithLifecycle() instead of collectAsState().
  9. supervisorScope isolates children so one child failure does not cancel its siblings; use it for independent tasks.
  10. flatMapLatest cancels the previous inner flow when the upstream key changes; mapLatest cancels a stale expensive computation.

APIs at a glance

API or termUse it for
suspendcompiler modifier that rewrites a function into a state machine with a Continuation parameter
launchstart a fire-and-forget child coroutine; returns a Job you can join() or cancel()
asyncstart a child coroutine that produces a value via Deferred<T>.await(); use for parallel calls to combine
withContextswitch dispatcher for a block and return the result to the caller's context; standard way to change dispatchers
coroutineScope / supervisorScopecoroutineScope cancels siblings on any child failure; supervisorScope isolates children so one failure does not stop the rest
StateFlow / MutableStateFlowconflated, always-has-value stream that skips equal values; use update { } for atomic read-modify-write
SharedFlow / MutableSharedFlowmulti-cast stream that delivers every value including duplicates; use for events, not state
flatMapLatestcancel the previous inner flow when the upstream key changes; standard for search fields and user-id switches
repeatOnLifecyclesuspend until DESTROYED; cancel the block below STARTED and restart at onStart; use in onViewCreated
collectAsStateWithLifecycleCompose collector that stops below STARTED; use it on Android instead of collectAsState, which keeps collecting in the background
flowOnmove upstream operators to a given dispatcher; affects only operators above it, not the collector
Channel + receiveAsFlowbuffer 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 viewModelScope or lifecycleScope over GlobalScope or a hand-made CoroutineScope; they tie cancellation to a real lifecycle.
  • Never swallow CancellationException; always rethrow it in catch blocks so the coroutine actually stops.
  • Prefer update { } over value = value + 1 for read-modify-write on StateFlow; update retries with compareAndSet and never loses an update.
  • Prefer withContext(Dispatchers.IO) over a raw Thread or Executor; the work then belongs to the calling coroutine's Job hierarchy and is cancellable.
  • Never call runBlocking on the main thread; it blocks the looper and produces the ANR you were trying to avoid.
  • Prefer repeatOnLifecycle(STARTED) or collectAsStateWithLifecycle() over lifecycleScope.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 CancellationException first.
  • 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: use update { }, which retries with compareAndSet.
  • Putting catch after flatMapLatest in a long-lived stream. The first upstream error completes the whole flow and the screen stops updating. Fix: put catch inside the inner flow so one failed request does not end the stream.
  • Collecting two flows one after another in the same coroutine. collect on a StateFlow never returns, so the second collect never starts. Fix: launch each collection in its own child coroutine inside repeatOnLifecycle.
  • 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 MutableStateFlow for state; model one-off events as state the UI acknowledges, or a Channel with 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 supervisorScope for 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.

Go deeper