Navigation 3 hands you the back stack as plain state. There is no controller to ask, no graph to inflate, no hidden NavBackStackEntry lifecycle you can only observe. You hold a list, you mutate the list, and the UI follows.
That is freedom. It is also a whole new class of bugs, because every guarantee the old library enforced quietly (one entry per destination, cleanup on pop, restoration after process death) is now your code. This post walks through the five places where teams get hurt: modeling nested flows, restoring after process death, scoping ViewModels, predictive back, and finding leaks before your users do.
The mental model: a list of keys and a function
Nav3 has two moving parts. Your keys are small immutable values that describe where the user is. A NavDisplay turns the list of keys into UI through an entry provider.
sealed interface Route : NavKey
@Serializable data object Home : Route
@Serializable data object Catalog : Route
@Serializable data class Product(val productId: String, val instanceId: String) : Route
@Composable
fun AppNav(navigator: Navigator, onFinish: () -> Unit) {
NavDisplay(
backStack = navigator.backStack,
onBack = { if (!navigator.pop()) onFinish() },
entryDecorators = listOf(
rememberSaveableStateHolderNavEntryDecorator(),
rememberViewModelStoreNavEntryDecorator(),
),
entryProvider = entryProvider {
entry<Home> { HomeScreen(onBrowse = { navigator.push(Catalog) }) }
entry<Catalog> { CatalogScreen(onOpen = { id -> navigator.push(Product(id, newId())) }) }
entry<Product> { key -> ProductScreen(key.productId) }
},
)
}
Decorator function names moved around between the alpha and beta releases. Check the exact names against the version you ship.
I wrap the raw NavBackStack in a tiny Navigator on purpose. The moment navigation is a mutable list, "just call add" spreads through the codebase, and the rules (no empty stack, no duplicate tops, flow-aware pops) need one home.
class Navigator(val backStack: NavBackStack<NavKey>) {
fun push(key: NavKey) {
if (backStack.lastOrNull() != key) backStack.add(key)
}
/** Returns false when only the root is left, so the caller can finish the Activity. */
fun pop(): Boolean {
// NavDisplay does not accept an empty stack, so the root is never removed here.
if (backStack.size <= 1) return false
backStack.removeLastOrNull()
return true
}
fun isFlowActive(flowId: String) =
backStack.any { it is FlowRoute && it.flowId == flowId }
fun completeFlow(flowId: String, next: NavKey) {
backStack.removeAll { it is FlowRoute && it.flowId == flowId }
backStack.add(next)
}
}
Failure mode: the empty stack. Remove the last key and NavDisplay throws on the next composition. Guard it in one place, and make the guard visible: pop() returns false when it refuses, and the host decides what "back on the root" means (usually Activity.finish(), as AppNav does through onFinish).
Nested flows without nested graphs
Old navigation expressed a checkout wizard as a nested graph. In Nav3 the flow is a property of the keys that belong to it. Nothing nests, and the stack stays flat.
interface FlowRoute : Route { val flowId: String }
@Serializable data class Address(override val flowId: String) : FlowRoute
@Serializable data class Payment(override val flowId: String) : FlowRoute
@Serializable data class Review(override val flowId: String) : FlowRoute
@Serializable data class Confirmation(val orderId: String) : Route
Starting a flow mints an id. Finishing it removes every key carrying that id, then pushes the destination, all in one callback so Compose sees a single state change.
fun startCheckout(navigator: Navigator) =
navigator.push(Address(flowId = UUID.randomUUID().toString()))
fun placeOrder(navigator: Navigator, flowId: String, orderId: String) =
navigator.completeFlow(flowId, next = Confirmation(orderId))
The flat model is simpler to reason about, but it removes the thing nested graphs gave you for free: a scope that lives exactly as long as the flow. We will rebuild that in the ViewModel section.
Failure mode: the flow that never ends. A user abandons checkout by tapping the bottom bar tab. If your tab switch replaces the stack with Home only, flow keys vanish, which is fine, but a tab switch that preserves per-tab stacks keeps the flow alive indefinitely. Decide per flow whether leaving it cancels it, and encode that in the navigator rather than in each screen.
Process death: the keys are all you get back
rememberNavBackStack stores your keys in saved state and rebuilds the list afterwards. Everything else is gone: ViewModels, in-memory caches, singletons.
val backStack = rememberNavBackStack(Home)
val navigator = remember(backStack) { Navigator(backStack) }
Keys are subtypes of an interface, so serialization needs to know the polymorphic hierarchy. The default rememberNavBackStack(Home) may resolve @Serializable subtypes on Android, but I would not rely on that: with a layered hierarchy like Route and FlowRoute, on a multiplatform target, or with R8 stripping serializers, a missing subtype fails at save time and only on the screen that uses it. Registering every key explicitly removes the whole category:
private val navConfig = SavedStateConfiguration {
serializersModule = SerializersModule {
polymorphic(NavKey::class) {
subclass(Home::class, Home.serializer())
subclass(Catalog::class, Catalog.serializer())
subclass(Product::class, Product.serializer())
subclass(Address::class, Address.serializer())
subclass(Payment::class, Payment.serializer())
subclass(Review::class, Review.serializer())
subclass(Confirmation::class, Confirmation.serializer())
}
}
}
val backStack = rememberNavBackStack(navConfig, Home)
Real-world failures I would test for before release:
-
A key you forgot to register. The checkout screens are the classic victim: the stack saves fine on Home and throws a
SerializationExceptiononly when the user is onPayment. Add a test that pushes every key type and recreates the Activity. - Fat keys. Putting a parcel-sized object in a key sends it through saved state. Keep keys to ids and primitives, and reload from a repository.
-
Stale ids. The restored
Product("42")may point to an item deleted while the process was dead. Validate the restored stack against current data and drop or redirect before the first frame. -
Logged-out restores. The stack still contains
Account, but the session expired. Run a guard over the restored list, not only over fresh navigation events. -
Defaults that never serialize.
kotlinx.serializationomits properties equal to their default value unless told otherwise. Aval instanceId = newId()default is regenerated differently on restore, and your entry identity silently changes. Pass such values explicitly, asProductdoes above. -
Reproduce it. Enable “Don’t keep activities” is not enough. Use
adb shell am kill <package>from the background and come back, with a flow deep in progress.
Scoping ViewModels per entry, and per flow
With the ViewModel-store decorator installed, viewModel() called inside an entry is scoped to that entry. It is created when the entry first composes and cleared when the entry leaves the back stack.
entry<Product> { key ->
val vm: ProductViewModel = viewModel(
factory = viewModelFactory { initializer { ProductViewModel(key.productId) } }
)
ProductScreen(vm)
}
Failure mode: two equal keys. Entries are identified by a content key, which by default comes from the key itself, and the decorators use it to store per-entry state. Two equal keys in one stack are not a supported configuration. Depending on the version and the decorators involved, you can get a crash from the saveable-state holder or entries that share state, and popping one then clears state the other still shows. That is why Product carries an instanceId, and why Navigator.push ignores a push equal to the current top. If you genuinely need duplicates, supply a distinct content key per entry.
A flow-scoped store
A checkout wizard wants one ViewModel shared by Address, Payment, and Review. Hoisting it to the Activity keeps it far too long; the entry scope is too short. So we build the missing middle: a ViewModelStoreOwner per flow id, released when the last key of that flow leaves the stack.
class FlowStores(
private val onReleased: (owner: Any, flowId: String) -> Unit = { _, _ -> },
) {
private val owners = HashMap<String, ViewModelStoreOwner>()
fun ownerFor(flowId: String): ViewModelStoreOwner =
owners.getOrPut(flowId) {
object : ViewModelStoreOwner { override val viewModelStore = ViewModelStore() }
}
fun release(flowId: String) {
owners.remove(flowId)?.let { owner ->
owner.viewModelStore.clear()
onReleased(owner, flowId)
}
}
fun releaseAll() = owners.keys.toList().forEach(::release)
}
// Debug builds can install a watcher here without main code depending on LeakCanary.
object FlowStoreHooks {
@Volatile var onReleased: (owner: Any, flowId: String) -> Unit = { _, _ -> }
}
// Activity-scoped, so it survives rotation and is cleared when the Activity finishes.
class FlowStoresHolder : ViewModel() {
val stores = FlowStores(onReleased = { owner, id -> FlowStoreHooks.onReleased(owner, id) })
override fun onCleared() = stores.releaseAll()
}
The scope composable provides the owner to its content and decides when to let go:
val LocalFlowOwner = compositionLocalOf<ViewModelStoreOwner> {
error("Read the flow ViewModel only inside FlowScope")
}
@Composable
fun FlowScope(
flowId: String,
stores: FlowStores,
isFlowActive: () -> Boolean,
content: @Composable () -> Unit,
) {
val owner = remember(flowId) { stores.ownerFor(flowId) }
val stillActive by rememberUpdatedState(isFlowActive)
DisposableEffect(flowId) {
onDispose { if (!stillActive()) stores.release(flowId) }
}
CompositionLocalProvider(LocalFlowOwner provides owner, content = content)
}
Usage inside an entry. The holder is requested in AppNav, outside any entry, so it resolves against the Activity's store:
// in AppNav, before NavDisplay
val stores = viewModel<FlowStoresHolder>().stores
// in the entry provider
entry<Payment> { key ->
FlowScope(key.flowId, stores, isFlowActive = { navigator.isFlowActive(key.flowId) }) {
val flowVm: CheckoutViewModel = viewModel(
viewModelStoreOwner = LocalFlowOwner.current,
factory = viewModelFactory { initializer { CheckoutViewModel(key.flowId) } },
)
PaymentScreen(flowVm)
}
}
Two details matter here. First, release happens in onDispose, which runs when FlowScope leaves composition. NavDisplay keeps a popped entry composed until its exit transition finishes, so the store is released after the animation rather than at the moment of the pop. Releasing from the pop call itself would clear the store while the outgoing screen is still visible. The rememberUpdatedState wrapper matters because the caller passes a fresh lambda on each recomposition, and onDispose must call the latest one. Second, a configuration change also disposes the composition, but the flow's keys are still on the stack, so isFlowActive() is true and nothing is released.
This custom owner has no SavedStateHandle. After process death the flow ViewModel starts empty, so persist wizard drafts to Room or DataStore keyed by flowId, and rebuild from there.
Predictive back
Enable the platform callback in the manifest, then let NavDisplay own back handling:
<application android:enableOnBackInvokedCallback="true" ... />
NavDisplay(
backStack = navigator.backStack,
onBack = { if (!navigator.pop()) onFinish() },
entryProvider = appEntryProvider(navigator), // the same provider as in AppNav
transitionSpec = {
slideInHorizontally { it } togetherWith slideOutHorizontally { -it / 4 }
},
popTransitionSpec = {
slideInHorizontally { -it / 4 } togetherWith slideOutHorizontally { it }
},
)
In earlier previews onBack took a count of entries to pop. Recent versions take no argument, so verify against your artifact version.
Things that bite in production:
-
The previous screen is composed mid-gesture. While the user drags, the destination underneath is already on screen. A
LaunchedEffect(Unit)that auto-redirects, fires analytics, or starts a request will run while the gesture can still be cancelled. Treat entry side effects as "may run and then be undone". -
A
BackHandlerthat is wrong at gesture start. A screen with unsaved changes registersBackHandler(enabled = dirty). Whether the system previews a pop or hands the gesture to your handler is decided by the state when the gesture begins, so adirtyflag updated asynchronously (after a debounce, say) leaves the user with the wrong behavior for that gesture. Deriveenabledsynchronously from hoisted state, and test the first back press right after an edit. -
Multi-step pops. If one back press should unwind a whole flow, route it through
completeFlowor a dedicatedpopFlowrather than loopingpop(); a loop produces several recompositions and a visible flicker. - Custom animation specs. Specs that depend on the target entry’s metadata must tolerate the mid-gesture state where the target is not yet committed.
Hunting leaks with LeakCanary
LeakCanary already watches destroyed Activities, Fragments, and cleared ViewModels. That covers entry-scoped ViewModels for free. It does not know that your FlowStores owner should be gone, so tell it, from debug code only:
// debug/ source set, registered as android:name in the debug manifest
class DebugApp : Application() {
override fun onCreate() {
super.onCreate()
FlowStoreHooks.onReleased = { owner, flowId ->
AppWatcher.objectWatcher.expectWeaklyReachable(owner, "Flow store $flowId was released")
}
}
}
// build.gradle.kts
debugImplementation("com.squareup.leakcanary:leakcanary-android:<version>")
androidTestImplementation("com.squareup.leakcanary:leakcanary-android-instrumentation:<version>")
Then make the leak a failing test, not a notification you may never open:
@get:Rule val composeRule = createAndroidComposeRule<MainActivity>()
@get:Rule val leaks = DetectLeaksAfterTestSuccess()
@Test fun completingCheckout_releasesFlowStore() {
composeRule.onNodeWithText("Checkout").performClick()
composeRule.onNodeWithText("Place order").performClick()
composeRule.onNodeWithText("Order confirmed").assertIsDisplayed()
}
If a ViewModel in the flow store holds anything that references the Activity, the test fails after the flow completes, with a leak trace that points at the retaining field.
What the traces usually show:
-
A singleton navigator holding the back stack and an Activity-captured lambda. Create the navigator with
rememberinside composition, and keep no static references. -
Keys that capture things. A key with a
Contextor callback is unserializable and retains what it captured. Keys are data. -
A ViewModel storing
onNavigate. The UI hands it a lambda; the ViewModel outlives the screen. Expose events or state and let the UI call the navigator. - The orphaned store from the previous section, if release is wired to the wrong moment.
Checklist before you ship
- Exactly one place mutates the back stack, and it refuses to empty it.
- Keys are serializable, tiny, and unique per entry.
- Flow identity lives in the key; flow state lives in a store with a defined release point.
- Restored stacks are validated against current auth and data.
- Entry side effects tolerate predictive back being cancelled.
- Leak tests cover completing, abandoning, and rotating through a flow.
Owning the back stack is genuinely better: navigation becomes testable, inspectable state. The price is that lifecycle, restoration, and cleanup are now your design decisions. Make them once, in one place, and test the unhappy paths.
🍎 Share Your Kotlin Code with iOS — Without Rewriting Your App
If “we’ll just build it twice, once per platform” describes how your team ships mobile, I’d recommend “Kotlin Multiplatform for Android Developers” — a 22-chapter, hands-on guide that goes past the sample-project demos and follows the shared module all the way to two app store submissions. No iOS or Swift background required.
It walks through the expect/actual mechanism and source set hierarchy, shared architecture, networking with Ktor, persistence with Room KMP and SQLDelight, Koin dependency injection, Flow and StateFlow with Swift interop (SKIE and Swift Export), Compose Multiplatform versus native SwiftUI, navigation, testing across two runtimes, dual-toolchain CI/CD with Linux and macOS runners, publishing a KMP library, and migrating an existing Android app module by module. Everything builds toward one capstone: an offline-first Expense/Budget Tracker, complete with a pending-sync queue, retry/backoff, and a deployment checklist for both stores.
- E-book: Available on Google Play
- Kindle Edition: Available on Amazon
- Topmate: Available on Topmate
- Also available in Paperback & Hardcover.




Top comments (0)