In a Jetpack ViewModel, why does screen state survive a rotation, and when does the ViewModelStore finally clear the ViewModel?
answer
- the owner keeps a store
- store outlives the recreated Activity
- same key, same instance, no factory call
- cleared on finish or on pop
- process death skips onCleared
basics
~20 sA ViewModel lives in its owner's ViewModelStore, which survives a configuration change, so the recreated Activity gets the same instance back. The store clears it, calling onCleared, only when the owner ends for good, such as a finished Activity or a popped navigation entry.
solid answer
~40 sA ViewModel is kept in the `ViewModelStore` of its `ViewModelStoreOwner`: an Activity, a Fragment, a navigation back-stack entry or a Navigation 3 entry. On a configuration change such as a rotation the Activity object is recreated, but its store is retained, so `by viewModels()` or Compose's `viewModel()` finds the existing instance under the same key and the factory is not called again; work already running in `viewModelScope` simply continues. The store is cleared only when the owner ends permanently: the Activity finishes, the Fragment is destroyed without being recreated, or the navigation entry is popped. Clearing closes the ViewModel's resources, which cancels `viewModelScope`, and then calls `onCleared()`. A system-initiated process death throws the whole store away with no `onCleared()` at all, which is why process-death state goes through `SavedStateHandle`.
go deeper
Recall that the ViewModel survives a rotation because its owner's store is kept, and that onCleared runs only when the Activity finishes or the entry is popped.
Explain the provider's lookup by key in the ViewModelStore, why the factory and init do not run again on rotation, and which events clear each kind of owner.
Diagnose leaks from Activity or View references held in a ViewModel, reloads caused by work started in onCreate, and state lost because the process died rather than the Activity.
Weigh how much screen state a team keeps only in ViewModel memory, given that process death discards it silently, against the cost of saving or persisting it.
## The owner, the store and the key A Jetpack **ViewModel** never lives on its own. Each instance is held in a **`ViewModelStore`**, a map from a key to a `ViewModel`, and that store belongs to a **`ViewModelStoreOwner`**. The everyday owners are a `ComponentActivity`, a `Fragment`, a Navigation `NavBackStackEntry` and a Navigation 3 entry. The ViewModel is said to be *scoped* to that owner: it lives exactly as long as the owner's store. When a screen asks for a ViewModel, through `by viewModels()` in an Activity, `viewModel()` in Compose or `ViewModelProvider(owner).get(...)`, the provider does three things: 1. It builds a key. By default that is the string `androidx.lifecycle.ViewModelProvider.DefaultKey:` followed by the class's canonical name, which is why requesting a local or anonymous class without an explicit key fails. 2. It looks the key up in the owner's store and, if it finds an instance of the requested class, returns it as is. 3. Only when nothing is stored does it call the **`ViewModelProvider.Factory`**, then put the new instance in the store. ## Why a rotation keeps the instance A rotation is a **configuration change**: the system destroys the Activity object and creates a new one with the new configuration. The `ViewModelStore` contract says the store "must be retained across configuration changes", and that the recreated owner reuses the previous store instance. When the new Activity's `onCreate` asks for the ViewModel again, step 2 finds it: - the factory is not called, so constructor code and `init` blocks do not run a second time; - fields keep their values, so the half-loaded screen state is still there; - coroutines running in `viewModelScope` keep going; the Android documentation says asynchronous work "continues in the ViewModel" across the change. That is the whole trick: the Activity is new, the store is old, and the key is the same. ## When the ViewModel is cleared | Owner | Its store is cleared when | |---|---| | `ComponentActivity` | the Activity finishes (Back, `finish()`), not when it is recreated | | `Fragment` | the Fragment is destroyed for good rather than recreated | | `NavBackStackEntry` | the entry is popped off the back stack | | Navigation 3 entry | the entry is popped off the back stack | Two common cases do **not** clear anything: pushing a new destination on top (the previous entry is still on the back stack) and sending the app to the background (the Activity is stopped, not finished). Clearing runs on the main thread. The store empties itself and, for each ViewModel, closes the `AutoCloseable` resources registered with it, which cancels `viewModelScope`, and finally calls **`onCleared()`**. A ViewModel that observes something long-lived releases that subscription there, or registers it as a closeable so the library releases it. ## What a ViewModel does not survive The store lives in the app's memory. When the system kills a backgrounded app's process to reclaim memory, the store disappears with everything else, and no callback runs, `onCleared()` included. The Android documentation puts it plainly: unlike saved state, ViewModels are destroyed during a system-initiated process death. State that must come back after that goes into the ViewModel's **`SavedStateHandle`**, or is reloaded from storage, while the wider comparison with an Activity's own saved instance state is a topic of its own. ## Rules that follow - **Never keep an Activity, Fragment, View or Activity `Context` in a ViewModel.** The ViewModel outlives the Activity object that a rotation destroys, so the reference leaks it. When the Application is needed, `AndroidViewModel` receives it in its constructor, or a factory reads it from `APPLICATION_KEY`. - **Never call the ViewModel's constructor from UI code.** The class documentation says never to create one outside a `ViewModelProvider.Factory`. An instance built directly is in no store: each recreated Activity builds another one and nothing ever clears the old one. - **Start one-time work where it runs once per ViewModel**, such as `init` or the first request for data, rather than in every `onCreate`, which runs again after each rotation. ```kotlin class BookingActivity : ComponentActivity() { // Same instance before and after a rotation private val viewModel: BookingViewModel by viewModels() } class BookingViewModel : ViewModel() { init { /* runs once per ViewModel, not once per Activity */ } override fun onCleared() { // Activity finished: release what the ViewModel still holds } } ```
- Why does a ViewModel created with its constructor inside onCreate not survive a rotation?Because it never enters a `ViewModelStore`. The provider only returns an instance it finds in the owner's store; a direct constructor call bypasses both the store and the factory. Each recreated Activity therefore builds a fresh object, the old one is never cleared, and nothing calls its `onCleared()` or cancels its `viewModelScope`.
- Does pushing a new destination on top clear the previous destination's ViewModel?No. The previous `NavBackStackEntry` stays on the back stack, so its store and ViewModel stay in memory while the new destination is shown, and going back finds the same instance. That store is cleared only when the entry itself is popped, for example when the user presses Back past it.
- How can a ViewModel use a Context without leaking an Activity?Extend `AndroidViewModel`, whose constructor receives the `Application`, or have the factory read the `Application` from `APPLICATION_KEY` and pass in Application-scoped dependencies. The Application lives as long as the process, so holding it leaks nothing; an Activity, a View or an Activity Context does.
A ViewModel is like luggage checked into a hotel's storage room: you can change rooms (rotate) and collect the same bag with your ticket, and the hotel only disposes of it when you check out (finish), while a fire that empties the building (process death) gives no notice at all.
- A new ViewModel is created on rotation and refilled from saved state.
- onCleared runs every time the Activity is destroyed, rotation included.
- The ViewModel survives the system killing the app's process in the background.
- Keeping the Activity in a ViewModel is fine because they share a lifecycle.
- Calling the ViewModel constructor in onCreate is equivalent to by viewModels().