In a multi-module Android app on Navigation Compose, would you keep one NavHost with a nested graph per feature module and type-safe routes as the module contract?
answer
- one controller, one back stack
- NavGraphBuilder extensions per feature
- route classes in a shared module
- graphs shape deep-link stacks
- callbacks, not NavController
basics
~20 sUsually yes: one NavHost in the app module, a nested graph per feature contributed through a NavGraphBuilder extension, and @Serializable routes in small shared modules. The price is contract modules and app-level wiring; extra NavHosts split the back stack.
solid answer
~50 sI default to a single `NavHost` owned by the app module. Each feature exposes `fun NavGraphBuilder.cartGraph(onCheckoutDone: () -> Unit)` that registers `navigation<CartGraph>(startDestination = Cart) { ... }`, and its `@Serializable` routes live in a small API module others may depend on, so search can call `navigate(ProductDetail(id))` without seeing the product feature's screens. One controller keeps one back stack, saved tab stacks, predictive back and deep links consistent, and nested graphs give per-flow `ViewModel` scope and the synthetic back stack for links. The costs: route classes become a public, versioned contract; the app module wires features together with lambdas instead of letting features call `NavController`; and graph shape changes deep-link behaviour. A second `NavHost` is justified only for an isolated sub-flow whose history should not join the app's, and it splits Back handling, so I would make it an exception.
go deeper
Recall that a NavHost owns one NavController and back stack, and that navigation<T>() groups destinations into a nested graph.
Explain how a feature contributes a graph through a NavGraphBuilder extension and why screens receive callbacks instead of the NavController.
Show how nested graph boundaries change deep-link back stacks, graph-scoped ViewModels and tab saving, and how route changes break callers at compile time.
Own the policy: one NavHost per activity, route modules as versioned contracts, when a second host is allowed, and how graph changes are reviewed and tested.
## The decision In a codebase with feature modules (catalogue, product, cart, checkout, account), someone must decide how Navigation Compose is assembled. The realistic options: | Option | Shape | Main cost | |---|---|---| | A. One `NavHost`, flat | every destination registered in the app module | app module knows every screen; no flow scoping | | B. One `NavHost`, nested graph per feature | each feature contributes `navigation<FeatureGraph>` | a shared route module and app-level wiring | | C. A `NavHost` per feature or tab | each has its own `NavController` | several back stacks to coordinate by hand | There is no single right answer for every app, but B is the usual default, and C is the exception to justify. ## Why one controller matters A `NavController` owns **one back stack**, and much of what Navigation does well depends on all destinations sharing it: - **Multiple back stacks for tabs** come from `popUpTo { saveState = true }` with `restoreState`, inside one controller. - **Deep links** are matched against the controller's graph, and the synthetic back stack is built from the **start destination of each enclosing nested graph**. - **System Back and predictive back** are handled by the `NavHost` for its controller. With several `NavHost`s (option C), each has its own stack. Back must be routed between them by hand, a deep link must know which host to target, and saving tab stacks is reinvented. That is sometimes worth it for a self-contained sub-flow, such as a multi-step wizard inside one screen whose history should not mix with the app's, but it should be rare. ## How option B looks in code Each feature module exposes a `NavGraphBuilder` extension and keeps its screens internal: ```kotlin // :feature:cart (implementation) fun NavGraphBuilder.cartGraph(onOpenProduct: (String) -> Unit, onPaid: () -> Unit) { navigation<CartGraph>(startDestination = Cart) { composable<Cart> { CartScreen(onOpenProduct = onOpenProduct) } composable<Checkout> { CheckoutScreen(onPaid = onPaid) } } } ``` The app module assembles the graph and wires features together: ```kotlin NavHost(navController, startDestination = HomeGraph) { homeGraph(onOpenProduct = { navController.navigate(ProductDetail(it)) }) productGraph(onAddedToCart = { navController.navigate(CartGraph) }) cartGraph( onOpenProduct = { navController.navigate(ProductDetail(it)) }, onPaid = { navController.popBackStack<CartGraph>(inclusive = true) }, ) } ``` ## Type-safe routes as the contract With type-safe routes (Navigation 2.8.0 and later), a route is a `@Serializable` class, and **that class is the contract** between modules: - Put each feature's route classes (`ProductDetail(val id: String)`, `CartGraph`) in a small **API module** that other features may depend on. The Kotlin Serialization plugin must be applied there, where the classes are declared. - A feature that wants to open another feature's screen depends only on the API module and receives a lambda, or navigates by route, without importing the target's implementation. - Changing a route's required arguments is a **breaking change** for every caller, and the compiler finds them all. That is the main benefit over string routes, which drift silently. - Arguments stay small (ids, enums); custom types need a `NavType` in `typeMap`, and that `NavType` must ship with the route. ## What nested graphs buy you 1. **Flow-scoped state.** A checkout `ViewModel` shared across steps can be scoped to the graph's entry with `navController.getBackStackEntry<CheckoutGraph>()`, and is cleared when the flow is popped. 2. **Atomic pops.** `popBackStack<CartGraph>(inclusive = true)` removes a whole flow after payment. 3. **Deep-link back stacks.** A link into Checkout builds the stack from the root's start destination down through each enclosing graph's start, so graph boundaries are product decisions, not just code organisation. 4. **Tab stacks.** Each tab as a nested graph is what `saveState` and `restoreState` save and restore as a unit. ## The costs a lead accepts - **App-module wiring grows.** Every cross-feature path is a lambda passed in the app module; that is the price of features not calling `NavController` directly, which the Navigation guide also recommends against. - **Contract discipline.** Route modules need owners, review rules and care when arguments change. - **Graph shape is behaviour.** Moving a destination between graphs changes deep-link stacks and `ViewModel` scope. Treat it as a behavioural change and test it. - **Mixed apps.** While screens are still Fragments, the guide recommends staying on Fragment-based navigation and moving the graph to Navigation Compose once the screens are composables; type-safe Compose routes cannot drive Fragment destinations directly. ## A reasonable policy - One `NavHost` per activity, owned by the app module. - One nested graph per feature or flow, contributed through a `NavGraphBuilder` extension. - Route classes in API modules; screens and `NavType`s beside them. - Screens receive callbacks, never the `NavController`. - A second `NavHost` only with a written reason. How navigation should be modelled as state, and how features should open each other in any mobile stack, is covered in the mobile system design material; this is the Navigation Compose version of that decision.
- Where should the @Serializable route classes live so that search can open product detail without depending on the product feature's implementation?In a small API module, such as the product feature's api module, that holds only `ProductDetail` and its `NavType`s, with the Kotlin Serialization plugin applied. Search depends on that module and calls `navigate(ProductDetail(id))`, or receives an `onOpenProduct` lambda from the app module. The product feature's screens stay internal to its implementation module.
- When would you accept a second NavHost in a Navigation Compose app?For a self-contained sub-flow whose history must not join the app's back stack, such as a wizard embedded in one screen. Its controller then owns its own stack, so you must route Back between hosts and decide how deep links reach it. Because that work recurs, I would require a written reason instead of allowing it by default.
- Every feature module should own its own NavHost and NavController
- Passing the NavController into every screen is the simplest contract
- Nested graphs are only folders and do not change runtime behaviour
- Callers should depend on the target feature's implementation module to reach its routes
- String routes are just as safe across modules as type-safe ones