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?
answer
- nearest owner wins
- each destination is its own owner
- one store per back-stack entry
- scope to the flow's parent entry
- an Activity scope outlives the flow
basics
~20 sCompose'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.
solid answer
~50 s`viewModel()` takes `LocalViewModelStoreOwner.current`, and inside a Navigation Compose destination that is the destination's own `NavBackStackEntry`. Three steps mean three entries, three `ViewModelStore`s and three ViewModels, so the extras step starts empty. The fix is to pick an owner whose lifetime matches the flow: put the steps in a nested graph and request the ViewModel from the graph's entry, `navController.getBackStackEntry(...)` remembered per entry and passed to `viewModel(owner)`. All three steps then share one instance, and it is cleared when the flow's graph is popped. Scoping to the Activity, with `activityViewModels()` from a Fragment, also shares it, but the store lives until the Activity finishes, so a second booking starts with the first one's car. In Navigation 3 each `NavEntry` gets its own owner from the lifecycle decorator and its store is cleared when the entry is popped, so a shared ViewModel needs an owner above those entries.
code
kotlin · 12 linesnavigation(startDestination = "dates", route = "booking") {
composable("dates") { /* DatesStep */ }
composable("car") { /* CarStep */ }
composable("extras") { backStackEntry ->
val flowEntry = remember(backStackEntry) {
navController.getBackStackEntry("booking")
}
// Same instance as the dates and car steps
val booking: BookingViewModel = viewModel(flowEntry)
ExtrasStep(booking)
}
}go deeper
Know that viewModel() picks the nearest ViewModelStoreOwner and that each navigation destination is an owner of its own.
Explain how activity, nested-graph and destination scopes differ in who shares the instance and when its store is cleared.
Diagnose an empty step caused by per-destination scope, stale data from Activity scope and state lost on pop, then pick the owner whose lifetime matches the flow.
Set a team convention for flow-level ViewModels, nested graphs or a dedicated owner, so shared state is cleared by navigation rather than by hand.
## Why each step gets a fresh instance Compose's `viewModel()` has a `viewModelStoreOwner` parameter whose default is `LocalViewModelStoreOwner.current`, the **nearest** owner in the composition. A navigation host provides a different owner for every destination: - in **Navigation Compose**, each destination's content runs with its own `NavBackStackEntry` as the owner; - in **Navigation 3**, the decorator from `lifecycle-viewmodel-navigation3` gives each `NavEntry` its own owner, keyed by the entry's `contentKey`. So the dates, car and extras steps each call `viewModel<BookingViewModel>()` against a different `ViewModelStore`. The provider finds nothing under the default key in the extras step's store and builds a new, empty ViewModel. Nothing is lost: the state was never shared. ## Choosing the owner The owner decides two things at once: **who shares** the instance and **when it is cleared**. For the booking flow: | Owner | Shared by | Cleared when | Fit for the flow | |---|---|---|---| | each step's `NavBackStackEntry` (the default) | one step | that step is popped | wrong: three instances | | the nested graph's `NavBackStackEntry` | every step inside the graph | the whole graph is popped | right: lives exactly as long as the flow | | the Activity (`activityViewModels()` in a Fragment, the Activity as owner in Compose) | every screen in the Activity | the Activity finishes | too long: stale data leaks into the next booking | | a Navigation 3 `NavEntry` | one entry | that entry is popped | per step only, like the default above | ## Scoping to the flow in Navigation Compose 1. Group the steps under a nested graph with its own route, for example `booking`. 2. In each step, look up the graph's entry with `navController.getBackStackEntry("booking")`, wrapped in `remember(backStackEntry)` so the lookup is tied to the current destination's entry. 3. Pass it as the owner: `viewModel(flowEntry)`. Every step now resolves the same store and key and gets the same instance. When the booking completes and the app pops the `booking` graph, that entry leaves the back stack, its store is cleared, `viewModelScope` is cancelled and `onCleared()` runs. The graph entry is also a saved-state owner, so the shared ViewModel's `SavedStateHandle` keeps the half-filled form across process death the same way a per-screen one would. ## Navigation 3 entries In Navigation 3 the `ViewModelStoreNavEntryDecorator` clears an entry's store when the entry is popped, and since Lifecycle 2.11 that is the only behaviour: the old `removeViewModelStoreOnPop` parameter is deprecated, ignored and never invoked. There is no nested-graph entry, so a ViewModel shared by several entries must come from an owner above them, such as the owner that was current outside the navigation display, captured before each entry provides its own. Lifecycle 2.11 also added `rememberViewModelStoreOwner()` and `rememberViewModelStoreProvider()`, which create owners tied to a composable's place in the UI; those are cleared when that composable leaves the composition. ## Traps that look like scoping bugs - **State lost on pop.** A ViewModel scoped to the dates step disappears when the user leaves that step for good, even though the car step wanted it. The fix is a wider owner, not keeping the step alive. - **State that will not go away.** An Activity-scoped booking ViewModel still holds last week's car because the Activity never finished. Either narrow the scope to the flow or reset the state explicitly when the booking completes. - **Two owners in one screen.** A component that calls `viewModel()` with the default owner while its screen passes the flow's entry gets a second instance. Pass the shared instance down, or pass the same owner. ## Confirming which owner you got Scoping bugs are invisible in the UI until data goes missing, so check the owner directly: 1. Log the ViewModel's identity (for example `System.identityHashCode(viewModel)`) in each step; one shared instance prints one value. 2. Log the owner's `viewModelStore`. Since Lifecycle 2.11 `ViewModelStore.toString()` lists the keys it holds, so the graph entry's store should show the booking ViewModel's key while each step's own store does not. 3. Pop the flow and confirm `onCleared()` runs once, which proves the instance was released with the flow and not kept by a wider owner. In a Fragment-based screen the same reasoning applies: `by viewModels()` scopes the ViewModel to the Fragment itself, `activityViewModels()` to its host Activity, and the owner you pass is the lifetime you get.
- When the booking graph is popped, what runs, and in which order?The graph's `NavBackStackEntry` leaves the back stack and its `ViewModelStore` is cleared. For the booking ViewModel, resources registered with a key are closed first, which cancels `viewModelScope`; then constructor and keyless closeables; finally `onCleared()` runs on the main thread.
- Why not keep the flow alive by scoping every booking ViewModel to the Activity?Because the Activity's store lives until the Activity finishes, which can span many bookings. The ViewModel keeps the previous car, dates and extras, keeps its loaded prices in memory, and must be reset by hand at the right moment. A flow-level owner gets clearing for free when the flow ends.
- viewModel() always returns the Activity's instance, so all steps already share it.
- The extras step is empty because the ViewModel was cleared when the car step opened.
- Activity scope is the safe default for any ViewModel two screens use.
- In Navigation 3, removeViewModelStoreOnPop returning false keeps an entry's ViewModel after pop.
- A shared ViewModel cannot use SavedStateHandle because it has no screen of its own.
Assumes Lifecycle 2.11, which added rememberViewModelStoreOwner and rememberViewModelStoreProvider, deprecated removeViewModelStoreOnPop and made ViewModelStore.toString() list its keys.