Navigation across modules

Learn navigation across Android feature modules with Navigation Compose: @Serializable type-safe routes, NavGraphBuilder extensions and app-module wiring. About 25 minutes.

Why it matters

  • In a multi-module Android app, "how does feature A open a screen in feature B without depending on it?" is a standard senior interview question.
  • A direct feature-to-feature dependency couples two teams' code, slows builds, and is one import away from a circular dependency that Gradle refuses to build.
  • Type-safe Navigation Compose routes (@Serializable classes, Navigation 2.8 and later) turn typos in route strings and wrong argument types into compile errors.
  • When each feature exposes its own NavGraphBuilder extension and navigation function, the feature can be built, tested and previewed on its own, and the app module stays a thin wiring layer.

The simple explanation

  • A shopping mall has many independent stores, each with its own layout and staff.
  • You cannot walk through a wall from store A to store B; you go out to the main hallway.
  • Each store puts a sign at its door saying how to enter (its route and navigation function).
  • Mall management (the app module) builds the hallway and decides which door leads where.

How do you navigate between feature modules in Android? Each feature module exposes three small things: its route (a @Serializable class), a navigation function on NavController (navigateToProfile(userId)), and a NavGraphBuilder extension that registers its screens (profileScreen(...)). The app module, which depends on every feature, creates the NavController and the NavHost and calls those extensions. When a profile screen needs to open settings, it does not call settings directly: it takes a callback such as onOpenSettings: () -> Unit, and the app module passes navController::navigateToSettings.

That way feature modules never depend on each other. Only the app module knows the whole graph.

If a feature really must build another feature's route itself (for example to pass a typed route into a deep-link helper), put the route classes in a small api module per feature (:feature:settings:api) that both can depend on, and keep the screens in the implementation module.

PieceLives inExample
RouteFeature module (or its api module)@Serializable data class ProfileRoute(val userId: String)
Navigation functionFeature modulefun NavController.navigateToProfile(userId: String)
Graph extensionFeature modulefun NavGraphBuilder.profileScreen(onBack: () -> Unit, ...)
NavHost and wiringApp moduleNavHost(navController, startDestination = HomeRoute) { ... }

With type-safe routes, composable<ProfileRoute> { ... } registers a destination, navController.navigate(ProfileRoute("42")) opens it, and backStackEntry.toRoute<ProfileRoute>() or savedStateHandle.toRoute<ProfileRoute>() reads the arguments back. The Kotlin serialization plugin generates the serializer that Navigation uses to build the route and its arguments.

Jetpack Navigation 3 is a separate, newer library with a different API (you own the back stack as a list). The module boundaries in this lesson apply to it too; the code here uses Navigation Compose.

Notes

  • Feature modules should not depend on other feature modules. Cross-feature navigation goes through callbacks that the app module wires.
  • Type-safe Navigation Compose (2.8+) uses @Serializable objects for routes without arguments and @Serializable data classes for routes with arguments. Apply the Kotlin serialization Gradle plugin in each module that declares routes.
  • Each feature exposes a route, a NavController.navigateToX(...) function and a NavGraphBuilder.xScreen(...) extension. Keep the screen Composables internal.
  • The app module owns the single NavController and the NavHost. Feature screens receive lambdas, not the NavController.
  • Pass IDs and small values as route arguments, then load the data in the destination's ViewModel from a repository. Arguments are saved in the back stack's saved state, so large objects bloat it.
  • Custom argument types (an enum is fine; a custom class is not) need a NavType passed through typeMap. Prefer primitive IDs.
  • In a ViewModel, read arguments with savedStateHandle.toRoute<ProfileRoute>(); in a Composable, with backStackEntry.toRoute<ProfileRoute>().
  • Group a multi-screen feature with navigation<SettingsGraph>(startDestination = SettingsHomeRoute) { ... } so other code can navigate to the feature as a whole.
  • Keep the NavController out of ViewModels. Expose UI state (for example isSaved = true) and let the screen call its navigation lambda when it sees that state.

Code example

A profile feature module exposes its route, navigation function and graph extension, and the app module wires it to the home and settings features.

// ===== :feature:profile =====
package com.example.feature.profile
 
import androidx.compose.runtime.Composable
import androidx.navigation.NavController
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavOptionsBuilder
import androidx.navigation.compose.composable
import androidx.navigation.toRoute
import kotlinx.serialization.Serializable
 
@Serializable
data class ProfileRoute(val userId: String)
 
fun NavController.navigateToProfile(
    userId: String,
    builder: NavOptionsBuilder.() -> Unit = {},
) {
    navigate(ProfileRoute(userId), builder)
}
 
fun NavGraphBuilder.profileScreen(
    onBack: () -> Unit,
    onOpenSettings: () -> Unit,
) {
    composable<ProfileRoute> { backStackEntry ->
        val route = backStackEntry.toRoute<ProfileRoute>()
        ProfileScreen(userId = route.userId, onBack = onBack, onOpenSettings = onOpenSettings)
    }
}
 
@Composable
internal fun ProfileScreen(userId: String, onBack: () -> Unit, onOpenSettings: () -> Unit) {
    // UI omitted
}
// ===== :app =====
package com.example.app
 
import androidx.compose.runtime.Composable
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.rememberNavController
import com.example.feature.home.HomeRoute
import com.example.feature.home.homeScreen
import com.example.feature.profile.navigateToProfile
import com.example.feature.profile.profileScreen
import com.example.feature.settings.navigateToSettings
import com.example.feature.settings.settingsScreen
 
@Composable
fun AppNavHost() {
    val navController = rememberNavController()
    NavHost(navController = navController, startDestination = HomeRoute) {
        homeScreen(onOpenProfile = { userId -> navController.navigateToProfile(userId) })
        profileScreen(
            onBack = { navController.popBackStack() },
            onOpenSettings = { navController.navigateToSettings() },
        )
        settingsScreen(onBack = { navController.popBackStack() })
    }
}
  • :feature:profile does not know that settings exists. It asks for an onOpenSettings lambda, and only :app turns that into navigateToSettings().
  • ProfileRoute carries only the user id; the profile ViewModel reads it with savedStateHandle.toRoute<ProfileRoute>() and loads the user from a repository.
  • ProfileScreen is internal, so other modules can only reach the screen through the route and the graph extension.
  • homeScreen, HomeRoute, settingsScreen and navigateToSettings follow the same pattern in their own feature modules.

Run the idea in plain Kotlin

There is no Navigation library here, so a tiny graph keyed by route class stands in for NavHost. Each "feature" registers its screen and gets callbacks; only main (the app module) connects them.

import kotlin.reflect.KClass

// ---- a minimal stand-in for NavHost and NavController ----
class Graph {
  val screens = mutableMapOf<KClass<*>, (Any) -> Unit>()
  val backStack = mutableListOf<Any>()

  fun <T : Any> register(type: KClass<T>, show: (T) -> Unit) {
      @Suppress("UNCHECKED_CAST")
      screens[type] = { route -> show(route as T) }
  }

  fun navigate(route: Any) {
      backStack += route
      screens.getValue(route::class)(route)
  }

  fun popBackStack() {
      backStack.removeAt(backStack.lastIndex)
      println("Back to " + backStack.last())
  }
}

// ---- feature: home ----
data object HomeRoute
fun Graph.homeScreen(onOpenProfile: (String) -> Unit) =
  register(HomeRoute::class) {
      println("Home screen")
      onOpenProfile("42") // user taps a profile
  }

// ---- feature: profile (knows nothing about settings) ----
data class ProfileRoute(val userId: String)
fun Graph.navigateToProfile(userId: String) = navigate(ProfileRoute(userId))
fun Graph.profileScreen(onOpenSettings: () -> Unit) =
  register(ProfileRoute::class) { route ->
      println("Profile screen for user " + route.userId)
      onOpenSettings() // user taps the settings icon
  }

// ---- feature: settings ----
data object SettingsRoute
fun Graph.navigateToSettings() = navigate(SettingsRoute)
fun Graph.settingsScreen() =
  register(SettingsRoute::class) { println("Settings screen") }

// ---- app module: the only place that knows every feature ----
fun main() {
  val graph = Graph()
  graph.homeScreen(onOpenProfile = { id -> graph.navigateToProfile(id) })
  graph.profileScreen(onOpenSettings = { graph.navigateToSettings() })
  graph.settingsScreen()

  graph.navigate(HomeRoute)
  println("Back stack: " + graph.backStack)
  graph.popBackStack()
}

Expected output:

Home screen
Profile screen for user 42
Settings screen
Back stack: [HomeRoute, ProfileRoute(userId=42), SettingsRoute]
Back to ProfileRoute(userId=42)

In production

Circular dependency from a navigation shortcut
  • A developer needed a button in settings that opens the profile screen, so they added implementation(project(":feature:profile")) to :feature:settings.
  • :feature:profile already depended on :feature:settings to open settings from the profile toolbar.
  • Gradle refused to build the cycle, and the pull request was blocked.
The fix
  • Both feature-to-feature dependencies were removed.
  • Each feature now exposes a route, a navigation function and a NavGraphBuilder extension, and takes callbacks like onOpenProfile and onOpenSettings.
  • The app module wires the callbacks to navigateToProfile and navigateToSettings, and a CI check rejects any new :feature:* to :feature:* dependency.
Whole objects passed as route arguments
  • A list screen passed the full Article (title, body, image URLs) to the detail screen as a custom route argument with its own NavType.
  • The saved state of the back stack grew with every opened article, and after a deep session the app crashed in the background with TransactionTooLargeException while saving state.
  • The detail screen also showed stale data, because it displayed the copy taken when the user tapped, not what was in the database.
The fix
  • The route became @Serializable data class ArticleRoute(val articleId: Long).
  • The detail ViewModel reads the id with savedStateHandle.toRoute<ArticleRoute>() and observes the article from the repository, so it always shows current data.
  • The custom NavType was deleted.

Common mistakes

  • Direct feature-to-feature dependency. Couples features and invites cycles. Take a callback and let the app module wire it, or depend on a small route-only api module.
  • Passing large objects in routes. Route arguments live in saved state, so big objects bloat it and can trigger TransactionTooLargeException. Pass an ID and load the data in the destination.
  • Hard-coded string routes. "profile/{id}" strings break on typos and wrong argument types at runtime. Use @Serializable route classes with Navigation 2.8+.
  • A NavHost in each feature module. Nested NavHosts with their own controllers make back handling and deep links hard. Features contribute destinations to the app's single NavHost (use navigation<Graph>(...) for nested graphs).
  • Passing the NavController into ViewModels or deep into screens. It ties logic to the UI framework and makes screens hard to preview and test. Pass lambdas such as onBack and onOpenSettings.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“How do you navigate between two feature modules in a multi-module Android app?”

“What does @Serializable give you in Navigation Compose?”

“Why shouldn't a feature module depend on another feature module?”

“How should a ViewModel trigger navigation?”

Quiz

Where should the NavHost live in a multi-module Navigation Compose app?

What makes a Navigation Compose route type-safe in Navigation 2.8 and later?

A list screen opens a detail screen for an article. What should the route carry?

The profile screen needs a button that opens settings, which lives in another feature module. What is the usual approach?

0 of 4 answered

Mini task

Wire two feature modules through the app module (20 min)

  1. Add routes. In :feature:profile, add @Serializable data class ProfileRoute(val userId: String). In :feature:settings, add @Serializable data object SettingsRoute. Apply the Kotlin serialization plugin in both modules.
  2. Expose navigation functions. Add fun NavController.navigateToProfile(userId: String) and fun NavController.navigateToSettings() next to each route.
  3. Expose graph extensions. Add fun NavGraphBuilder.profileScreen(onBack: () -> Unit, onOpenSettings: () -> Unit) using composable<ProfileRoute> and toRoute(), and fun NavGraphBuilder.settingsScreen(onBack: () -> Unit). Make the screen Composables internal.
  4. Wire the app. In :app, create a NavHost and call both extensions, passing lambdas such as onOpenSettings = { navController.navigateToSettings() } and onBack = { navController.popBackStack() }.
  5. Read the argument in the ViewModel. In ProfileViewModel, read the id with savedStateHandle.toRoute<ProfileRoute>().

Done condition: neither feature module's build.gradle.kts mentions the other, the app opens profile and then settings from the profile button, and back returns to profile.

Next: Feature flags and remote config