Android from the foundation · Puzzle 18 · 19 of 20
The ViewModel outlives the screen
In puzzle 17, turning the phone threw away the Activity and everything in its fields. Here's the object made to survive that, and where it waits while the new Activity is built.
The problem
In puzzle 17, a configuration change replaced your Activity with a new one, and the counter in its fields went back to 0. Now imagine the field held a list that took two seconds to download. Every time the user turns the phone, it's gone, and you download it again. The process survived: is there somewhere in it that outlives one Activity object?
See it
Keep the counter in a ViewModel, an object made to hold one screen's data. Each Activity keeps its ViewModels in a ViewModelStore: a small map, name → ViewModel.
Step 1 of 4The phone turns, and the old Activity is destroyed. But first
ActivityThreadWhen an Activity is destroyed only to be recreated, ActivityThread keeps what it hands over (including the ViewModelStore), then gives it to the new Activity in attach(). 6119 if (getNonConfigInstance) { 6120 r.lastNonConfigurationInstances = r.activity.retainNonConfigurationInstances(); … 4180 activity.attach(…, r.lastNonConfigurationInstances, config, …);ActivityThread.java, lines 6120 and 4180 · AOSP frameworks/base ↗, Android's own code in your process, takes the store and holds it. Predict: what will the new Activity's counter show?Step 2 of 43. The new Activity is handed the same store, with the same ViewModel inside. Nothing crossed Binder: it all stayed in your process.
Step 3 of 4When the user leaves the screen for good with Back, no new Activity is coming. The store is emptied, and each ViewModel's
onCleared()runs.Step 4 of 4
The building block
A ViewModel is an object made to hold one screen's data. You write it as a class built on ViewModel, and it can do the slow work itself, like the download:
class ListViewModel : ViewModel() {
val items = startDownload() // starts once, when the ViewModel is created, on another thread (puzzle 15)
}
// in the Activity:
val vm: ListViewModel by viewModels()
The word by in that last line hands the job of finding the ViewModel to viewModels(), which doesn't create a new one each time. Each Activity keeps its ViewModels in a ViewModelStore: a small map from a name to a ViewModel. viewModels() looks in the store first and creates the ViewModel only if it isn't there yet.
The trick is what happens to the store. When the Activity is destroyed only to be recreated, ActivityThreadWhen an Activity is destroyed only to be recreated, ActivityThread keeps what it hands over (including the ViewModelStore), then gives it to the new Activity in attach(). 6119 if (getNonConfigInstance) {
6120 r.lastNonConfigurationInstances = r.activity.retainNonConfigurationInstances();
…
4180 activity.attach(…, r.lastNonConfigurationInstances, config, …);ActivityThread.java, lines 6120 and 4180 · AOSP frameworks/base ↗ (puzzle 14), Android's code in your process that carries out system_server's orders, like "destroy" and "create", keeps the store and hands it to the new Activity. Same store, same ViewModel, same count. Nothing crosses Binder: it all stays in your process's memory.
When the Activity is destroyed for good, for example the user pressed the Back button to leave the screen, no new Activity is coming. Then the store is cleared, and each ViewModel's onCleared() runs: your chance to stop work it started, like an unfinished download. The code that ships with ViewModel decides between the two with one check: at destroy, clear the store only if isChangingConfigurations is false (it's true when this destroy is only to recreate the Activity).
So a ViewModel lives as long as the user keeps that screen: the screen they see stays the same, while the Activity objects behind it are replaced. But it still lives in your process. If the process itself is gone, so is the ViewModel. What survives that is puzzle 19.
The analogy
Before the room is torn down to be rebuilt, the clerk carries its locker out and sets it in the new room. If the room is closed for good, the locker is emptied instead.
Check yourself
Sources
- AndroidX source: ComponentActivity (on
ON_DESTROY:if (!isChangingConfigurations) { viewModelStore.clear() }; the new Activity takes the store fromlastNonConfigurationInstance) - AndroidX source: ViewModelStore (a
mutableMapOf<Any?, ViewModel>()) - AOSP: ActivityThread.java (
r.lastNonConfigurationInstances = r.activity.retainNonConfigurationInstances(), then passed toactivity.attach(…)) - Android Developers: ViewModel overview
What you now know
A ViewModel lives in its Activity's ViewModelStore. On a configuration change, ActivityThread keeps the store and hands it to the new Activity, all inside your process. When the screen closes for good, the store is cleared and onCleared() runs.
Answer every question above correctly to unlock the next puzzle.
Something wrong or unclear on this page? Tell me: a puzzle that didn't click is a bug in the puzzle.