Skip to content
Dark title card reading Android Kotlin coroutines: scopes, dispatchers, cancellation, part 1 of the Kotlin for Android developers series

Android Kotlin coroutines: scopes, dispatchers, cancellation

Table of Contents
  1. How structured concurrency ties jobs to a scope
  2. Which scope to use on Android
  3. Dispatchers and main-safe functions
  4. Cancellation is cooperative
  5. runCatching swallows CancellationException
  6. Cleanup with finally and NonCancellable
  7. (Advanced) Job vs SupervisorJob and exception propagation
  8. (Advanced) Testing coroutines with runTest
  9. Gotchas

Most Android code launches coroutines the same way every time: viewModelScope.launch, then withContext(Dispatchers.IO) somewhere inside. That works until a download keeps going after the user leaves the screen, or a save gets cut off halfway.

Choose the scope whose lifetime matches the work, and call withContext(Dispatchers.IO) inside the function that blocks, not at the call site. Cancellation in Kotlin coroutines is cooperative, so code must reach a suspend call or ensureActive() to notice it. On Android it most often breaks when runCatching swallows CancellationException.

Work Scope Why
Load data for a screen viewModelScope Survives rotation, cancelled when the screen is gone for good
Collect a flow in an Activity or Fragment lifecycleScope + repeatOnLifecycle(STARTED) Stops collecting in the background, restarts on return
Finish a short write after the screen closes An injected application CoroutineScope Lives as long as the process
Work that must survive process death WorkManager The OS reschedules it

TL;DR

  • Repositories own withContext(io), with the dispatcher injected.
  • Long CPU loops call ensureActive(). Broad catches rethrow CancellationException.
  • Test with runTest, Dispatchers.setMain and ViewModelStore.clear().

What you’ll learn

  • Why some coroutines keep running after cancel(), with real output.
  • How cleanup and failures travel through a scope.
  • How to test that clearing a ViewModel cancels its work.

You should have launched coroutines in a ViewModel before. The sections up to cleanup are the core path, and the 2 “(Advanced)” sections go deeper. Examples use Kotlin 2.4.21, kotlinx.coroutines 1.11.0 and AndroidX Lifecycle 2.11.1.

How structured concurrency ties jobs to a scope

Every coroutine launched in a scope becomes a child of that scope’s Job. A coroutine started inside another one becomes its child in turn. Cancelling a parent cancels all of its children, and a parent does not finish until its children do.

Tree of jobs: viewModelScope, cancelled in onCleared, has two children, launch refresh and launch search. The refresh job has two children of its own, withContext(IO) calling api.fetch and async reading the cache. A GlobalScope.launch box sits apart from the tree, drawn with a dashed border

When the ViewModel is cleared, one cancel() reaches the refresh, the search and everything they started. GlobalScope has no parent to cancel it. Here are 2 children of a scope and one GlobalScope job, with the scope cancelled after 250 ms:

child A tick 2
GlobalScope tick 2
-- screen.cancel()
GlobalScope tick 3
GlobalScope tick 4
done

Both children stop. The GlobalScope job ticks on, still holding whatever it captured, the ViewModel included.

Warning: GlobalScope.launch, or a CoroutineScope(Job()) created in a class and never cancelled, leaks work past the screen with nothing able to stop it. Work that must outlive the screen needs a scope with a known owner.

Which scope to use on Android

viewModelScope is the default for screen data. It is cancelled when the ViewModel’s onCleared() runs, which happens when the user leaves the screen for good. Rotation does not clear it. The Android architecture post covers the ViewModel side of this.

lifecycleScope with repeatOnLifecycle is for collecting flows in an Activity or Fragment. repeatOnLifecycle(STARTED) starts its block when the lifecycle reaches STARTED and cancels it when the lifecycle drops below. Each time the app comes back, it starts the block again.

ArticlesActivity.kt (excerpt)
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.state.collect { render(it) }
}
}
Kotlin

I ran this against a LifecycleRegistry in a JVM test and changed the state by hand. prices is a MutableStateFlow, and the value 3 was set while the lifecycle sat at CREATED:

collector started
render 1
render 2
collector stopped
collector started
render 3
collector stopped

Nothing was rendered in the background, and the new collector got the latest value on return. The older launchWhenStarted is still in Lifecycle 2.11.1 but marked @Deprecated, because it only paused the block and kept the upstream flow active. In Compose, collectAsStateWithLifecycle() does this job for you (recomposition covers what happens next).

An injected application scope is for short work the user expects to finish after the screen closes, such as saving a draft when they press Back. Create it once, in the Application class or your DI graph, as CoroutineScope(SupervisorJob() + Dispatchers.Default). Then pass it to the repository that needs it:

DraftRepository.kt (excerpt)
class DraftRepository(
private val appScope: CoroutineScope, // lives as long as the app process
private val io: CoroutineDispatcher,
) {
suspend fun save(text: String) {
appScope.launch(io) { dao.insert(Draft(text)) }.join()
}
}
Kotlin

The caller still waits through join(). If the caller is cancelled, only the waiting stops, while the write carries on in appScope. I tested this with the DAO replaced by a 300 ms delay and the ViewModel cleared 100 ms in. The first test uses the appScope repository. The second writes directly in viewModelScope:

ScopesTest > draftSurvivesViewModelClear() STANDARD_OUT
saved after clear: [half-written note]
NaiveScopeTest > draftLostWithViewModelScope() STANDARD_OUT
saved after clear: []

This only covers the process staying alive. If the work has to survive the app being killed, use WorkManager.

Dispatchers and main-safe functions

A dispatcher decides which threads run a coroutine. Main is the UI thread, IO is a large pool for blocking calls such as file access, and Default has as many threads as CPU cores (at least 2) for computation like parsing JSON.

I follow one rule here. A suspend function should be safe to call from the main thread, so the function that blocks switches threads itself:

DefaultArticleRepository.kt
class DefaultArticleRepository(
private val api: ArticleApi,
private val io: CoroutineDispatcher = Dispatchers.IO,
) : ArticleRepository {
override suspend fun load(): List<String> = withContext(io) { api.fetchTitles() }
}
Kotlin

Should you inject the dispatcher or call Dispatchers.IO directly? I inject it, as a constructor parameter or a small DispatcherProvider, so a test can pass a test dispatcher. In my test the fake API printed fetchTitles on Test worker @kotlinx.coroutines.test runner#2, so no real thread pool was involved. Calling Dispatchers.IO directly is fine in a small app without tests. With Hilt, a qualifier annotation and a small module provide it.

Retrofit and Room suspend functions are already main-safe, so you do not need to wrap them in withContext(IO). If one slow dependency should not take over the whole IO pool, Dispatchers.IO.limitedParallelism(4) gives it a view with at most 4 threads.

Cancellation is cooperative

Calling cancel() does not stop a thread. It marks the job as cancelling, and the coroutine only stops when it next checks. Every suspend function in kotlinx.coroutines (delay, withContext, yield, join) checks for you. A loop that never suspends never checks.

This experiment runs 5 steps of 50 ms of pure CPU work and cancels after 120 ms. The first loop has no check. The second calls ensureActive() at the top of each step:

val cooperates = launch(Dispatchers.Default) {
repeat(5) { i ->
ensureActive() // throws CancellationException once cancelled
busyWork() // about 50 ms of CPU
println("cooperates: step $i")
}
}
delay(120)
cooperates.cancelAndJoin()
Kotlin
ignores: step 0
ignores: step 1
cancel ignores
ignores: step 2
ignores: step 3
ignores: step 4
ignores finished
cooperates: step 0
cooperates: step 1
cancel cooperates
cooperates: step 2
cooperates finished

The loop without the check ran all 5 steps while cancelAndJoin() waited. The cooperative loop finished the step in progress and stopped at the next check. The check runs only between steps, so if one step is long, check inside it too. Use if (!isActive) break when you want to return a partial result.

For time limits, withTimeout(500) cancels the block and throws TimeoutCancellationException (“Timed out waiting for 500 ms”), while withTimeoutOrNull(500) returns null.

runCatching swallows CancellationException

When a coroutine is cancelled, the suspend call it is waiting on throws CancellationException, and that exception travelling up the stack is how the coroutine stops. A broad catch stops it travelling. Here a loop fetches 5 pages through runCatching, and the job is cancelled during the second fetch:

val job = launch {
repeat(5) { n ->
val result = runCatching { fetchPage(n) }
println("runCatching -> $result, isActive=$isActive")
}
println("loop finished, saving to disk...")
}
delay(150)
job.cancelAndJoin()
Kotlin
runCatching -> Success(page 0), isActive=true
-- job.cancel()
runCatching -> Failure(kotlinx.coroutines.JobCancellationException: StandaloneCoroutine was cancelled; …), isActive=false
…
loop finished, saving to disk...

The same Failure line appeared for pages 1 to 4, then the “save to disk” line ran on a cancelled job. Each fetchPage failed at once because delay saw the cancellation, and runCatching turned it into a value. catch (e: Exception) behaves the same way.

Warning: do not wrap a suspend call in runCatching or catch (e: Exception) unless you rethrow CancellationException. Searching the codebase for runCatching { finds most of them.

There are 2 fixes. The better one is to catch only what you expect, such as IOException or HttpException. When you do want a Result, use a version that lets cancellation through:

suspend inline fun <T> suspendRunCatching(block: () -> T): Result<T> =
try { Result.success(block()) }
catch (e: CancellationException) { throw e }
catch (e: Exception) { Result.failure(e) }
Kotlin

With that change, the same loop prints Success(page 0) and stops at the cancel without reaching the save.

Cleanup with finally and NonCancellable

A finally block runs when a coroutine is cancelled, which makes it the place to close resources. A suspend call inside it is a problem, though, because the coroutine is already cancelled and the call throws straight away. Here 2 coroutines try to save a draft in finally, and only the second wraps the call in withContext(NonCancellable):

finally {
withContext(NonCancellable) { saveDraft("guarded") }
}
Kotlin
plain: finally starts
guarded: draft saved

The plain version lost the save without any error message. Nothing can cancel a NonCancellable block, so keep it to a short write or a close call, and move anything longer to the application scope.

(Advanced) Job vs SupervisorJob and exception propagation

A failing child does more than fail. With a plain Job, the child’s exception cancels the parent, and the parent cancels every sibling. A SupervisorJob lets the failure stay with that child. viewModelScope and lifecycleScope both use SupervisorJob, so a failed refresh does not kill a running search.

In this experiment one child throws after 50 ms while its sibling needs 200 ms. Both scopes have a CoroutineExceptionHandler:

Job: sibling cancelled
Job handler caught: avatar upload failed
Job: scope active=false
SupervisorJob handler caught: avatar upload failed
SupervisorJob: sibling finished
SupervisorJob: scope active=true

Under Job the scope is dead after one failure, and a later launch on it does nothing. Under SupervisorJob the sibling finished. The handler ran because the failing coroutine was launched directly in the scope. A CoroutineExceptionHandler only runs for root coroutines, and on a child it is ignored, because the child hands its exception to its parent. Inside coroutineScope { } one failing async still cancels the others, which is usually what you want for parallel loads.

(Advanced) Testing coroutines with runTest

runTest runs on virtual time, so delay(1_000) takes no real time. viewModelScope runs on Dispatchers.Main.immediate, which a JVM test does not have, so the test replaces Main with Dispatchers.setMain. The ViewModel’s work then runs on the test scheduler, where advanceTimeBy controls it. A StandardTestDispatcher queues new coroutines until you advance the scheduler, so you can inspect the loading state. An UnconfinedTestDispatcher runs them eagerly, which is fine when only the final state matters.

ArticlesViewModelTest.kt (excerpt)
@BeforeTest fun setUp() = Dispatchers.setMain(StandardTestDispatcher())
@AfterTest fun tearDown() = Dispatchers.resetMain()
@Test fun clearingViewModelCancelsLoad() = runTest {
val repo = SlowRepository() // delay(1_000), sets cancelled = true on CancellationException
val store = ViewModelStore()
val vm = ViewModelProvider.create(store, viewModelFactory {
initializer { ArticlesViewModel(repo) }
})[ArticlesViewModel::class]
vm.refresh()
advanceTimeBy(500)
store.clear() // the screen is gone for good
advanceUntilIdle()
println("cancelled=${repo.cancelled}, state=${vm.state.value}")
assertTrue(repo.cancelled)
assertTrue(vm.state.value.isLoading)
}
Kotlin

ViewModelStore.clear() is the public way to trigger onCleared() from a test, and the whole thing runs as a plain JVM unit test without Robolectric. Here is the run, together with a second test that checks the state before and after the 1-second load:

ArticlesViewModelTest > loadsAfterOneSecond() STANDARD_OUT
after runCurrent: ArticlesState(items=[], isLoading=true, error=null)
after 1001 ms: ArticlesState(items=[Scopes, Dispatchers], isLoading=false, error=null)
ArticlesViewModelTest > clearingViewModelCancelsLoad() STANDARD_OUT
cancelled=true, state=ArticlesState(items=[], isLoading=true, error=null)
BUILD SUCCESSFUL in 17s

The state stays at isLoading=true after clearing, which is correct because nothing will render it again. An error state there would mean a broad catch turned the cancellation into an error.

Gotchas

  • GlobalScope or an uncancelled CoroutineScope(Job()) leaks work past the screen.
  • runCatching and catch (e: Exception) around suspend calls swallow cancellation. Rethrow it or catch narrower types.
  • A CPU loop without ensureActive() or yield() ignores cancel().
  • Suspend calls in finally throw after cancellation. Use withContext(NonCancellable) for short cleanup only.
  • A CoroutineExceptionHandler on a child coroutine is ignored.
  • launchWhenStarted is deprecated. Use repeatOnLifecycle in views and collectAsStateWithLifecycle() in Compose.

The pillar post on native and Flutter explains where Kotlin fits in my mobile work. If Flutter is next for you, Dart for Kotlin developers compares async/await with coroutines. The next post in this series, StateFlow vs SharedFlow, covers what to put in the flows you now collect safely.