skip to content

ViewModel & Saved State

ViewModel holds screen state across configuration changes, scoped to an Activity, Fragment or back-stack entry, and SavedStateHandle carries it past process death. Interviewers probe both limits.

on this pageshow

explore

questions

6

In a Jetpack ViewModel, why does screen state survive a rotation, and when does the ViewModelStore finally clear the ViewModel?

level: juniorimportance: must knowfreq 82%

answer

  1. the owner keeps a store
  2. store outlives the recreated Activity
  3. same key, same instance, no factory call
  4. cleared on finish or on pop
  5. process death skips onCleared

basics

~20 s

A 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 s

A 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

for a junior

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.

for a middle

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.

for a senior

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.

for a principal

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().
open as a page

In a Jetpack ViewModel, how does SavedStateHandle keep a half-filled car-rental booking form across process death, and what are its limits?

level: middleimportance: must knowfreq 74%

basics

~20 s

SavedStateHandle is a key-value map the ViewModel receives in its constructor; it is written into the owner's saved state when the Activity stops and restored after process death. It holds only Bundle-compatible values, and loses them when the user removes the task.

open as a page

In Jetpack Lifecycle, how do you write a ViewModelProvider.Factory with CreationExtras for a ViewModel needing a repository, a branch id and a SavedStateHandle?

level: middleimportance: should knowfreq 40%

basics

~20 s

Define viewModelFactory { initializer { } } whose lambda reads the Application from APPLICATION_KEY, the branch id from a custom CreationExtras.Key and calls createSavedStateHandle(). Pass the branch id in extras built on the owner's default extras.

open as a page

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?

level: seniorimportance: should knowfreq 46%

basics

~20 s

viewModelScope 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.

open as a page

With Jetpack ViewModel in a three-step car-rental booking flow, each step's viewModel() call gets a fresh instance and the extras step sees an empty form; why, and which ViewModelStoreOwner should own it?

level: seniorimportance: should knowfreq 52%

basics

~20 s

Compose's viewModel() uses the nearest ViewModelStoreOwner, and in a navigation host that is each step's own back-stack entry, so each step gets its own instance. Scope the shared ViewModel to an owner spanning exactly the flow, such as the flow's parent graph entry.

open as a page

For Jetpack ViewModel and SavedStateHandle, what team rule would you set for which state is saved in the handle and which is reloaded after process death?

level: principalimportance: should knowfreq 33%

basics

~20 s

Save in SavedStateHandle only small user input and the ids needed to rebuild the screen; reload everything derivable from those ids through the data layer. Persist to disk whatever must survive the user closing the task, and test the rule with simulated process death.

open as a page