skip to content

In Navigation 3, after adding rememberViewModelStoreNavEntryDecorator to NavDisplay, the tank gallery forgets its scroll position and search text whenever the user returns from a tank; why, and what is the fix?

level: seniorimportance: should knowfreq 35%

answer

  1. a parameter with a default list
  2. passing a list replaces it
  3. one decorator is called required
  4. first in the list wraps the rest
  5. state keyed and cleared by contentKey

basics

~10 s

Passing entryDecorators replaces NavDisplay's default list, which held rememberSaveableStateHolderNavEntryDecorator, so entries lose their rememberSaveable state when they leave the screen. List the saveable decorator again, first, then the ViewModel decorator.

solid answer

~40 s

`NavDisplay`'s `entryDecorators` parameter defaults to `listOf(rememberSaveableStateHolderNavEntryDecorator())`. Writing `entryDecorators = listOf(rememberViewModelStoreNavEntryDecorator())` does not append to that default, it replaces it. The saveable decorator wraps each entry in a `SaveableStateProvider` keyed by the entry's `contentKey`; without it, the gallery's `rememberSaveable` state, including its lazy list scroll position and search text, is discarded when the gallery leaves composition. The fix is `listOf(rememberSaveableStateHolderNavEntryDecorator(), rememberViewModelStoreNavEntryDecorator())`. Order matters: the first decorator in the list wraps the others, and the ViewModel decorator's documentation says it requires the saveable decorator so entry-scoped ViewModels can provide `SavedStateHandle`s. Both clear their state through `onPop` once the last entry with that `contentKey` is popped and has left composition.

code

kotlin · 13 lines
kotlin
NavDisplay(
    backStack = backStack,
    onBack = { backStack.removeLastOrNull() },
    entryDecorators = listOf(
        // Passing a list replaces the default, so list the saveable one again, first
        rememberSaveableStateHolderNavEntryDecorator(),
        rememberViewModelStoreNavEntryDecorator(),
    ),
    entryProvider = entryProvider {
        entry<TankGallery> { TankGalleryScreen() }
        entry<TankDetail> { key -> TankDetailScreen(key.tankId) }
    },
)

go deeper

for a junior

Recall that NavDisplay saves each screen's rememberSaveable state through its default saveable entry decorator, and that the ViewModel decorator comes from a separate lifecycle library.

for a middle

Explain decorate and onPop, why passing a list replaces the default, and why the saveable decorator must come first.

for a senior

Diagnose silent state loss from a replaced decorator list, explain when onPop fires relative to exit animations, and reason about entries that share a contentKey.

for a principal

Set a team rule for one shared decorator list built in one place, so feature code cannot drop the required decorator, and review custom decorators for what state they hold and when they release it.

## What a NavEntryDecorator is A `NavEntryDecorator<T>` wraps the content of every `NavEntry` that NavDisplay renders. It has two parts: - **`decorate`**, a composable that receives the entry and calls `entry.Content()` inside whatever it provides, usually a `CompositionLocalProvider` or a state holder. It runs only for entries that are actually being rendered. - **`onPop`**, a cleanup callback that receives the entry's `contentKey` and runs only when all three hold: an entry was popped, it was the **last** entry on the stack with that `contentKey`, and its content has **left composition**, which means after any exit animation. Decorators are how per-entry scopes are built: saved UI state, `ViewModelStore`s, results, anything you write yourself with `NavEntryDecorator(onPop = ...) { entry -> ... }`. ## Why the gallery forgets `NavDisplay`'s parameter is declared as: ```kotlin entryDecorators: List<NavEntryDecorator<T>> = listOf(rememberSaveableStateHolderNavEntryDecorator()) ``` The library calls this decorator the only **required** one, because saving state is not optional. It wraps each entry in `SaveableStateHolder.SaveableStateProvider(entry.contentKey)`, so `rememberSaveable` calls inside an entry are saved under that key when the entry leaves composition and restored when it comes back. In a single-pane layout the gallery leaves composition every time a tank opens on top of it. Supplying `entryDecorators = listOf(rememberViewModelStoreNavEntryDecorator())` throws the default away. The gallery's `rememberLazyListState()` and its `rememberSaveable` search text no longer have a per-entry holder, so when the gallery is disposed their values go with it and come back as initial values on return. Nothing crashes, which is why this ships. The tell in a bug report is selective loss: data the gallery keeps in its entry-scoped ViewModel comes back, because the ViewModel decorator is still there, while everything held in `rememberSaveable`, scroll position included, starts over. That pattern points at the decorator list, not at the screen's code. ## The correct wiring 1. Keep `rememberSaveableStateHolderNavEntryDecorator()` in the list, and put it **first**. 2. Add `rememberViewModelStoreNavEntryDecorator()` from `androidx.lifecycle:lifecycle-viewmodel-navigation3` after it. 3. Add any custom decorator where its position fits: the list is folded so that the **first decorator is the outermost wrapper** and each later one sits inside it. Order matters for the ViewModel decorator because it builds each entry's `ViewModelStoreOwner` with the `LocalSavedStateRegistryOwner` it finds around it, which the saveable decorator provides per entry. Its documentation states that it requires `SaveableStateHolderNavEntryDecorator` so that entry-scoped ViewModels can properly provide `SavedStateHandle`s. When those ViewModels are cleared and what `onCleared` sees belongs to the ViewModel material. ## What each decorator does on pop | Decorator | Scope it provides | `onPop(contentKey)` does | |---|---|---| | `SaveableStateHolderNavEntryDecorator` | a saved-state slot per `contentKey` | `removeState(contentKey)` | | `ViewModelStoreNavEntryDecorator` | a `ViewModelStoreOwner` per `contentKey` | clears that key's store | Because cleanup waits until the popped entry has left composition, an entry that is animating out keeps its state until the animation ends; meanwhile NavDisplay caps that entry's `Lifecycle` at `CREATED`. ## contentKey is the identity Every decorator keys its state by `NavEntry.contentKey`, not by list position. Since Navigation 3 1.2 the default `contentKey` combines `key.toString()` with the key's class, so two `data object`s with the same name in different interfaces no longer collide. Two consecutive entries for an equal key, say `TankDetail("reef")` pushed twice, still share one `contentKey`, so they share decorator state and one ViewModel, and cleanup waits for the last of them. Because a `contentKey`, whether the default or one returned by the `clazzContentKey` lambda of `entry<K>`, is derived from the key, equal keys always share; give such keys a distinguishing field, such as a visit id, when each visit needs its own state. ## Writing your own decorator A custom decorator is a `NavEntryDecorator(onPop = { contentKey -> ... }) { entry -> ... }`. Typical uses: - provide a per-entry value through a `CompositionLocalProvider` around `entry.Content()`; - keep a per-entry object in a map keyed by `entry.contentKey`, and remove it in `onPop`; - wrap every entry in shared chrome that must not be duplicated in each screen. Because `decorate` runs only for entries being rendered, it is the wrong place for work that must happen for every key on the stack; and because `onPop` waits for composition to end, cleanup is safe even during exit animations. ## Traps in review - A custom decorator list that omits the saveable decorator. - The ViewModel decorator listed before the saveable one. - Using the `removeViewModelStoreOnPop` parameter: in lifecycle 2.11 it is deprecated and ignored, because configuration changes are handled internally. - Expecting `rememberNavBackStack` to save screen state: it saves keys only.

  • When exactly does a decorator's onPop run for the tank-detail entry?
    Only when three conditions hold: the entry was popped from the back stack, it was the last entry with that `contentKey`, and its content has left composition. A detail screen sliding out keeps its saved state and ViewModel until the exit animation ends; then the saveable decorator calls `removeState` and the ViewModel decorator clears that key's store.
  • Why can two TankDetail("reef") entries pushed one after another share a ViewModel?
    Decorators key their state by `contentKey`, and the default is built from the key's `toString()` and class, so equal keys produce equal content keys. The two entries share saved state and one `ViewModelStore`, and cleanup waits for the last one. Because `clazzContentKey` also derives from the key, the fix is a distinguishing field in the key itself, such as a visit id, when each visit needs its own state.
  • What happened to removeViewModelStoreOnPop in lifecycle-viewmodel-navigation3 2.11?
    It is deprecated and ignored: the lambda is never invoked. It was a workaround for detecting configuration changes, which the decorator now handles internally, and all decorator state is meant to clear together on pop. To keep decorator state outside one NavDisplay, the deprecation message points to `rememberDecoratedNavEntries`.

  • Passing a decorator to entryDecorators adds it to NavDisplay's default decorators.
  • The order of entryDecorators does not matter because each decorator is independent.
  • rememberViewModelStoreNavEntryDecorator works the same with or without the saveable decorator.
  • rememberNavBackStack already saves each screen's rememberSaveable state.
  • A popped entry's state is cleared the instant its key leaves the list, mid-animation.

Assumes Navigation 3 1.2 with lifecycle-viewmodel-navigation3 2.11; the composite default contentKey arrived in 1.2.0 (backported to 1.1.6).