In a Jetpack ViewModel, why does a viewModelScope.launch inside onCleared never run, and in what order are closeables, the scope and onCleared torn down?
answer
- the scope is itself a closeable
- keyed resources close first
- onCleared comes last
- a cancelled scope starts nothing
- Dispatchers.Main.immediate plus SupervisorJob
basics
~20 sviewModelScope is registered as a keyed AutoCloseable, and clearing closes keyed resources first, then constructor and keyless ones, and only then calls onCleared. By then the scope is cancelled, so a coroutine launched there is cancelled before its body runs.
solid answer
~40 s`viewModelScope` is created lazily with `SupervisorJob()` and `Dispatchers.Main.immediate` and stored on the ViewModel with `addCloseable` under an internal key. When the owner's store is cleared, the ViewModel runs a fixed sequence on the main thread: close resources added with a key, `viewModelScope` among them; close the ones passed to the constructor; close the ones added without a key; then call `onCleared()`. So inside `onCleared()` the scope's job is already cancelled, and `viewModelScope.launch { saveDraft() }` creates a coroutine that is cancelled before its body executes. Cleanup that must finish goes elsewhere: synchronous release in `onCleared()` or a closeable, and work that must outlive the screen in a scope that outlives the ViewModel, such as an application-level scope. `addCloseable` after clearing closes the resource immediately.
code
kotlin · 20 linesclass BookingViewModel(
private val drafts: DraftStore,
private val priceSocket: PriceSocket, // an AutoCloseable
) : ViewModel(priceSocket) {
fun refreshPrices() {
viewModelScope.launch { // Dispatchers.Main.immediate
val quote = withContext(Dispatchers.IO) { drafts.loadQuote() }
showQuote(quote)
}
}
override fun onCleared() {
// Bug: viewModelScope was cancelled in step 1 and priceSocket
// closed in step 2, so this body never runs.
viewModelScope.launch { drafts.saveDraft() }
}
private fun showQuote(quote: Quote) { /* update state */ }
}go deeper
Recall that viewModelScope is cancelled when the ViewModel is cleared and that it runs on the main thread by default.
Explain the four-step clearing sequence, keyed closeables before constructor and keyless ones, then onCleared, and how addCloseable behaves after clearing.
Diagnose saves launched from onCleared, resources used after they were closed, and slow work running on Dispatchers.Main.immediate without withContext.
Decide which work may die with the screen and which must move to a longer-lived scope, and make that a review rule for every ViewModel.
## What viewModelScope is **`viewModelScope`** is an extension property on `ViewModel`. The first access creates a `CoroutineScope` whose context is: - a **`SupervisorJob`**, so one failing child does not cancel its siblings; - **`Dispatchers.Main.immediate`**, so a coroutine started from the main thread begins at once on it. Where no main dispatcher exists, on some non-Android Kotlin Multiplatform targets, the scope falls back to `EmptyCoroutineContext`. Access is thread-safe, and the scope is stored on the ViewModel with **`addCloseable(key, ...)`** under an internal key. Closing it cancels its job. Since Lifecycle 2.8 a ViewModel can also receive its scope through the `ViewModel(viewModelScope: CoroutineScope)` constructor, for example to inject a different dispatcher; that scope is registered under the same key. Blocking or slow work inside it still switches with `withContext`, for example to `Dispatchers.IO`. ## The clearing sequence When the owner ends for good, its `ViewModelStore` calls each ViewModel's internal `clear()`, which runs on the main thread in this documented order: 1. close resources added **with** a key through `addCloseable(key, closeable)`, which includes `viewModelScope`; 2. close resources passed to the **constructor** (`ViewModel(vararg closeables)`); 3. close resources added **without** a key through `addCloseable(closeable)`; 4. call **`onCleared()`**. An exception thrown by a resource's `close()` is rethrown wrapped in `RuntimeException`. Once cleared, the ViewModel is marked as cleared and its resources are not closed a second time. ## Why the launch in onCleared does nothing By step 4 the scope's job is cancelled. `viewModelScope` still returns that same cancelled scope, because the closed resource stays registered under its key. Launching into a cancelled scope creates a child that is cancelled immediately; with the default start mode its body never runs. Nothing crashes and nothing is logged, which is why the draft silently never saves. The same applies to work launched before clearing: a price refresh still suspended in `viewModelScope` when the user finishes the Activity is cancelled in step 1, at its next suspension point. ## Where cleanup belongs | Need | Put it in | |---|---| | release a socket, a listener or a cache | an `AutoCloseable` passed to the constructor or `addCloseable`, or synchronous code in `onCleared()` | | stop collecting a flow started in `viewModelScope` | nothing extra: cancelling the scope stops it | | save a draft that must finish | a scope that outlives the ViewModel, such as an application-level scope or a background job, started while the ViewModel is still alive | | test teardown | inject the scope through the constructor so the test controls it | Two more rules from the source: - **`addCloseable` after clearing** closes the resource immediately instead of storing it, so a late registration does not leak. - **Replacing a keyed closeable** with `addCloseable(sameKey, newOne)` closes the old one at once. Since Lifecycle 2.11 `onCleared()` is annotated `@EmptySuper`: overrides need not call `super.onCleared()`. A short checklist for an `onCleared()` override follows from the order: - keep it synchronous and short, because it runs on the main thread while the screen is being torn down; - do not use resources that were registered as closeables, because they are already closed; - do not launch into `viewModelScope`, because it is already cancelled; - prefer registering a closeable over writing `onCleared()` at all, so release does not depend on an override. ## What Main.immediate means for the work itself The dispatcher choice shapes how code in the scope behaves while the ViewModel is alive: 1. `viewModelScope.launch { ... }` called from the main thread starts running **immediately**, in the same call, up to its first suspension point; nothing is posted to the message queue first. 2. Code before that first suspension runs on the main thread, so a blocking repository call placed there freezes the UI; it belongs inside `withContext(Dispatchers.IO)` or behind a suspending API that switches threads itself. 3. After `withContext` returns, the coroutine resumes on the main thread, where updating screen state is safe. The `SupervisorJob` means one failed price request does not cancel the other children of the scope. An exception nobody catches is still reported as uncaught, which on Android crashes the app; the failure-handling rules belong to coroutine exception handling in general. ## Reading it in code The snippet shows the bug and the order. The socket passed to the constructor closes in step 2, after the scope is cancelled and before `onCleared()`, so `onCleared()` must not use it either.
- What happens to a price refresh still suspended in viewModelScope when the user finishes the Activity?The Activity's store is cleared, the scope is closed in the first step of clearing, and the coroutine is cancelled: it throws `CancellationException` at its next suspension point and its `finally` blocks run. It does not continue in the background, and a result arriving later is never delivered.
- Why might a team inject the scope through the ViewModel constructor instead of using the default?Since Lifecycle 2.8 the `ViewModel(viewModelScope)` constructor lets the caller choose the dispatcher and job, which makes tests and non-main-thread setups explicit. The library still registers that scope under the same key, so it is cancelled at the same point in clearing as the default one.
- onCleared runs first, so it can still launch work in viewModelScope.
- viewModelScope runs on Dispatchers.Default unless you switch it.
- A coroutine in viewModelScope finishes its work after the Activity finishes.
- Calling addCloseable after clearing throws IllegalStateException.
- Every onCleared override must call super.onCleared() or resources leak.
Assumes Lifecycle 2.11; the CoroutineScope constructor overload arrived in 2.8, closing late closeables immediately in 2.7, and onCleared's @EmptySuper annotation in 2.11.