Skip to content

Lesson 5 of 9 · 28m

Coroutines and Flows: Cancellation Is a Feature

Structure asynchronous work with scopes, supervisors, cancellation, and flow operators instead of leaking callbacks and duplicate jobs.

Kotlin coroutines are easy to start and hard to reason about when nobody knows who owns them. The most expensive production bugs are not syntax errors; they are jobs that outlive the screen, mutations arriving after navigation, duplicate sync workers, and exceptions swallowed by the wrong scope. Learn structured concurrency as an ownership model, not a replacement keyword for threads.

Scopes express lifetime

viewModelScope is cancelled when the ViewModel is cleared. lifecycleScope follows the lifecycle owner. rememberCoroutineScope follows composition. None of them is appropriate for work that must survive the app process:

fun refresh() {
    viewModelScope.launch {
        uiState.value = uiState.value.copy(loading = true)
        runCatching { repository.refresh() }
            .onFailure { uiState.value = uiState.value.copy(error = it.message) }
    }
}

If closing the screen should cancel the work, this is correct. If the work writes critical state or uploads a file, screen lifetime is probably the wrong owner.

Cancellation is cooperative

A coroutine does not stop because the scope was cancelled if it never checks for cancellation. Kotlin's suspension points cooperate automatically:

suspend fun importRows(rows: List<Row>) = withContext(Dispatchers.Default) {
    rows.forEach { row ->
        ensureActive()
        database.insert(row.toEntity())
    }
}

CPU-heavy loops need explicit cancellation checks. Blocking I/O does not magically become cancellable; use library APIs and interrupt-aware implementations rather than pretending.

Flow is a pipeline, not a fancy callback

Operators create powerful behavior but can hide semantics:

query
    .debounce(300)
    .distinctUntilChanged()
    .flatMapLatest { repository.search(it) }

flatMapLatest cancels the previous search when the query changes — usually exactly what a search box needs. flatMapMerge does not. collectLatest abandons slow processing for a new value; collect does not. Read these operators as concurrency decisions, not ornamentation.

Exception behavior depends on scope shape

A regular child failure cancels its parent and siblings. supervisorScope isolates child failure:

supervisorScope {
    val avatar = async { runCatching { api.avatar() } }
    val orders = async { api.orders() }
    OrdersScreenState(orders.await(), avatar.await().getOrNull())
}

Do not install broad CoroutineExceptionHandler blocks and call it resilience. They do not catch cancellation or exceptions inside many async paths, and they often turn programming errors into silent stale UI.

Field notes

  • GlobalScope is usually a confession that nobody decided who owns the work.
  • Never update UI state after verifying only that a job exists; check cancellation and current state before mutation.
  • Dispatchers.IO is not an infinite thread pool; parallelism is still bounded and shared.
  • Unit tests need deterministic dispatchers and virtual time, otherwise every race becomes a flaky CI ritual.
  • Cancellation of a network request does not undo server-side effects; idempotency remains your problem.

Was this lesson helpful?

Sign in to rate