skip to content

In Navigation 3, how do rememberNavBackStack, NavKey and @Serializable keep a back stack through rotation and process death, and what breaks?

level: middleimportance: should knowfreq 45%

answer

  1. the stack is yours to save
  2. a marker interface plus an annotation
  3. class name written beside the value
  4. reflection on Android, a module elsewhere
  5. fails at save time, not compile time

basics

~20 s

rememberNavBackStack saves the list of keys with the Activity's saved state, so it survives rotation and process death. Every key must implement NavKey and be @Serializable; a key missing the annotation still compiles but fails when the stack is saved.

solid answer

~40 s

Because the app owns the back stack, saving it is the app's job, and `rememberNavBackStack(TankGallery)` is the convenience for it. It returns a `NavBackStack<NavKey>` and saves it through kotlinx.serialization: on Android the no-configuration overload writes each key's fully qualified class name plus the key encoded by its own serializer, and restores it by looking the class up with reflection, so no registration is needed. That only works when every key implements the `NavKey` marker interface **and** carries `@Serializable`; implementing `NavKey` alone compiles, then fails at runtime the first time state is saved. A `remember { mutableStateListOf(...) }` stack is rebuilt from scratch when the Activity is recreated. The stack saves keys only: each screen's `rememberSaveable` state comes from the saveable entry decorator, and ViewModel state follows ViewModel rules.

code

kotlin · 20 lines
kotlin
@Serializable data object TankGallery : NavKey
@Serializable data class TankDetail(val tankId: String) : NavKey
// Compiles, but saving fails once this key is on the stack
data class FeedingTimes(val tankId: String) : NavKey

@Composable
fun AquariumApp() {
    // Rebuilt from scratch whenever the Activity is recreated:
    // val backStack = remember { mutableStateListOf<NavKey>(TankGallery) }

    // Saved with the Activity's state, restored after rotation and process death:
    val backStack = rememberNavBackStack(TankGallery)
    NavDisplay(
        backStack = backStack,
        entryProvider = entryProvider {
            entry<TankGallery> { GalleryScreen(onOpen = { id -> backStack.add(TankDetail(id)) }) }
            entry<TankDetail> { key -> TankDetailScreen(key.tankId) }
        },
    )
}

go deeper

for a junior

Recall the two requirements on every key, implement NavKey and add @Serializable, and that rememberNavBackStack is what survives rotation and process death.

for a middle

Explain how the Android overload writes the class name and value and restores by reflection, why a missing annotation only fails at save time, and how this differs from a plain remember.

for a senior

Separate what is saved where: keys by the stack, per-entry UI state by the saveable decorator, ViewModel data by SavedStateHandle. Keep keys to ids and catch unserializable keys with a rotation test.

for a principal

Choose where the stack lives, composition, a ViewModel or a sealed typed stack, and set the team rule that every key is a small @Serializable NavKey, because one careless key turns into a crash on rotation.

## Why saving is the app's job In Navigation 3 the back stack is a list the app creates and edits, so the library cannot quietly persist it the way a controller-owned stack would be. A stack that lives only in `remember { mutableStateListOf<NavKey>(TankGallery) }` is lost twice over: - on a **configuration change** that recreates the Activity, such as rotation, because `remember` keeps nothing once the composition is rebuilt; - after **process death**, when the system kills a backgrounded app and later restores its task from saved state. Either way the user lands back on the gallery instead of the tank they were reading about. `rememberNavBackStack` exists to fix exactly this. ## What rememberNavBackStack needs from a key 1. The key implements **`NavKey`**, a marker interface. It exists because `@Serializable` is only an annotation: without a shared type there would be no single serializer for "any key on this stack". 2. The key class or object is annotated **`@Serializable`**, which needs the Kotlin serialization compiler plugin and `kotlinx-serialization-core`. 3. The key carries **small, stable data**: an id such as `tankId`, not a loaded `Tank` object, because the whole list is written into the Activity's saved state. `rememberNavBackStack(vararg elements: NavKey)` takes the initial keys and returns a `NavBackStack<NavKey>`, a `MutableList` backed by a `SnapshotStateList`, so NavDisplay observes it like any other snapshot list. ## How the Android overload saves and restores The overload without a configuration is Android-only. It serializes the stack with `NavBackStackSerializer` and, for each element, `NavKeySerializer`: | Step | What happens | |---|---| | Save | writes the key's fully qualified class name (`type`), then the key encoded with that class's own serializer (`value`) | | Restore | reads the class name, finds the class with `Class.forName`, gets its serializer by reflection, decodes the value | Because the class name is stored, keys of unrelated types can share one stack without being registered anywhere. The cost is that a key without a generated serializer is only discovered when the lookup runs, at save time. ## The multiplatform overload `rememberNavBackStack(configuration: SavedStateConfiguration, vararg elements: NavKey)` avoids reflection, which other platforms lack. Its `SavedStateConfiguration` must carry a `SerializersModule` that registers every `NavKey` subtype for polymorphic serialization; passing a configuration with the default module fails a `require` check with `IllegalArgumentException` that tells you to use `polymorphic(NavKey::class) { ... }`. How serializers modules work belongs to the kotlinx.serialization material. ## What breaks, and what is not saved - **A key without `@Serializable`.** The compiler accepts `data class FeedingTimes(val tankId: String) : NavKey`, because `rememberNavBackStack` only asks for `NavKey`. Nothing fails until the Activity saves its state, on rotation or when the app goes to the background; then the serializer lookup for that class throws and the app crashes. - **Large keys.** Every key is written into saved state, so objects belong in a repository, looked up by the id the key carries. - **Per-screen UI state.** The stack saves keys, not what each screen remembered. Scroll positions and text typed into a tank's notes are saved per entry by `SaveableStateHolderNavEntryDecorator`, which `NavDisplay` installs by default. - **ViewModels.** An entry-scoped ViewModel survives rotation but not process death; restoring its data is a `SavedStateHandle` question for the ViewModel material. ## Proving it before users do 1. Rotate on the deepest screen: the same tank should still be on top. 2. Turn on the developer option **Don't keep activities**, leave the app and come back, which recreates the Activity from saved state. 3. Put the app in the background, kill its process from a terminal with `adb shell am kill` and the package name, then return through Recents: the stack should come back with the same keys. 4. In a UI test, push every key type once and recreate the Activity, so a key without `@Serializable` fails in CI instead of on a device. ## Typed stacks and other homes `rememberNavBackStack` always returns `NavBackStack<NavKey>`. The save-state guide shows how to keep a narrower type: declare `@Serializable sealed interface AquariumKey : NavKey`, then write your own remember function that calls `rememberSerializable(serializer = serializer()) { NavBackStack(*elements) }`. A sealed hierarchy also lets the compiler know every subtype. The stack can live in a `ViewModel` instead; the guide notes that keys must still be serializable and that you then save and restore them yourself for process death.

  • When do you need the rememberNavBackStack overload that takes a SavedStateConfiguration?
    When the code must run outside Android, for example in a Kotlin Multiplatform module. The plain overload relies on `Class.forName` reflection, which only Android provides. The configuration overload requires a `SerializersModule` that registers every `NavKey` subtype with `polymorphic(NavKey::class) { ... }`; passing a configuration with the default module throws `IllegalArgumentException`.
  • How do you keep a NavBackStack<AquariumKey> instead of NavBackStack<NavKey>?
    Declare `@Serializable sealed interface AquariumKey : NavKey`, make every key implement it, and write your own remember function as the save-state guide does: `rememberSerializable(serializer = serializer()) { NavBackStack(*elements) }`. You get typed `add` calls, and the sealed hierarchy gives the compiler the full list of subtypes.
  • After process death, does rememberNavBackStack also bring back the notes a user typed on a tank's detail screen?
    Not by itself: it restores keys only. Text kept with `rememberSaveable` inside the entry comes back because NavDisplay's default `SaveableStateHolderNavEntryDecorator` saves each entry's state under its `contentKey`. Text kept in a plain `remember` or only in a ViewModel field is lost.

  • Implementing NavKey alone is enough for rememberNavBackStack to save a key.
  • A key missing @Serializable is rejected by the compiler.
  • A back stack held in remember { mutableStateListOf(...) } survives rotation.
  • rememberNavBackStack also saves every screen's rememberSaveable state.
  • On Android every NavKey subtype must be registered in a SerializersModule.