Compose Multiplatform Navigation, State & Testing
Use this skill to design, implement, and test navigation, lifecycle, ViewModel state management, deep links, and UI/localization tests in Compose Multiplatform projects targeting Android, iOS, Desktop (JVM), and Web (Wasm/JS).
Core Cross-Platform Rules
- No reflection on non-JVM targets (iOS, Web):
- ViewModel: Never call
viewModel()with zero arguments incommonMain. Always supply an initializer lambda (viewModel { MyViewModel() }) or explicit factory. - Navigation 3: Never use the reflection-based
rememberNavBackStack(RouteA)overload in cross-platform code. Always pass aSavedStateConfigurationwith aSerializersModule(or userememberSerializablewith asealed interface : NavKey).
- ViewModel: Never call
- Desktop
Dispatchers.Main.immediaterequirement:- Both
Lifecycle.coroutineScopeandViewModel.viewModelScoperely onDispatchers.Main.immediate. Whenever targeting Desktop (jvmMain), addorg.jetbrains.kotlinx:kotlinx-coroutines-swingtojvmMain.dependencies.
- Both
- Navigation 3 does not auto-scope ViewModels:
- Pass both
rememberSaveableStateHolderNavEntryDecorator()andrememberViewModelStoreNavEntryDecorator()toNavDisplay(entryDecorators = ...)so ViewModels and Compose state are scoped per navigation entry rather than leaking to the rootActivity/owner.
- Pass both
- Pass minimal route data:
- Pass only IDs, URIs, or primitive keys in route arguments. Never pass domain objects, bitmaps, app state, or
ViewModelinstances; load full data from the data layer at the destination.
- Pass only IDs, URIs, or primitive keys in route arguments. Never pass domain objects, bitmaps, app state, or
- Web URLs must stay in
#fragments (by default):- When customizing browser URLs in
bindToBrowserNavigation { ... }, prefix every returned route string with#and parsewindow.location.hashbefore callingbindToBrowserNavigation(). On Kotlin/JS (jsMain), wrapComposeViewportinsideonWasmReady {}.
- When customizing browser URLs in
- Treat external deep link URIs as untrusted input:
- Validate and sanitize all parsed deep link arguments. Cache incoming URIs in a
commonMainsingleton (ExternalUriHandler) so cold-start URIs arriving before composition are not dropped.
- Validate and sanitize all parsed deep link arguments. Cache incoming URIs in a
- Common UI tests use
runComposeUiTest, not JUnitTestRule:- Put shared tests in
commonTestusingandroidx.compose.ui.test.v2.runComposeUiTestand run Android UI tests via./gradlew :<module>:connectedAndroidTest(local Android unit-test gutter icons do not work).
- Put shared tests in
Workflow Decision Trees
1. Choosing a Navigation Approach
Need navigation in Compose Multiplatform?
├─ Compose Multiplatform >= 1.10 AND want user-owned SnapshotStateList back stack,
│ low-level Compose building blocks, or Material 3 Adaptive multi-pane layouts?
│ └─ Use Navigation 3 (`org.jetbrains.androidx.navigation3:navigation3-ui`)
│ ├─ Single module -> `sealed interface Route : NavKey` + `subclassesOfSealed<Route>()`
│ ├─ Multi-module (feature sealed types) -> aggregate `subclassesOfSealed<FeatureX>()` in app module
│ └─ Multi-module (decoupled routes) -> combine per-module `SerializersModule` with `+`
│ -> Read references/navigation-3.md
├─ Need mature deep linking, NavHost/NavController, or built-in experimental Web browser history?
│ └─ Use Navigation 2 (`org.jetbrains.androidx.navigation:navigation-compose`)
│ ├─ Standard routing, arguments, back stack, iOS/Desktop back gestures -> Read references/navigation-2.md
│ └─ Web `bindToBrowserNavigation()` & custom `#` URL mapping -> Read references/navigation-routing-web.md
└─ Need native iOS Liquid Glass navigation chrome or specialized third-party architecture?
└─ Keep Compose for screen content + native SwiftUI navigation, OR evaluate Voyager/Decompose/Circuit/Appyx/PreCompose
-> Read references/navigation-2.md
2. Wiring Lifecycle & ViewModel
What are you sharing across platforms?
├─ Shared ViewModel + Shared Compose UI
│ ├─ Add `org.jetbrains.androidx.lifecycle:lifecycle-viewmodel-compose` (+ `lifecycle-runtime-compose` for Lifecycle)
│ ├─ Add `kotlinx-coroutines-swing` in `jvmMain` if targeting Desktop
│ ├─ Instantiate via `viewModel { MyViewModel() }`, `koinViewModel()` (Koin), or `metroViewModel()` (Metro)
│ └─ If using Navigation 3, add `lifecycle-viewmodel-navigation3` and entry decorators on `NavDisplay`
│ -> Read references/viewmodel.md and references/lifecycle.md
├─ Shared ViewModel + Native Platform UI (Jetpack Compose / SwiftUI)
│ ├─ Expose `androidx.lifecycle:lifecycle-viewmodel` via `api(...)` and `export(...)` to iOS framework
│ └─ On iOS, bridge to SwiftUI with `KMP-ObservableViewModel` (`@NativeCoroutinesState` + `@StateViewModel`)
│ -> Read references/viewmodel.md
└─ Shared Repository / Data Layer Only
└─ Keep data/repos in `commonMain`; use native Android `ViewModel` + Hilt and Swift `ObservableObject` + `@StateObject`
-> Read references/viewmodel.md
Lifecycle platform quirks to watch:
- Web (Wasm/JS) skips
CREATEDand never reachesDESTROYED(tab close terminates the page). - iOS maps
UIViewController& app active/background notifications toON_START/ON_RESUME/ON_PAUSE/ON_STOP/ON_DESTROY. - Desktop maps Swing window focus/iconify/dispose callbacks.
- See full mapping tables in references/lifecycle.md.
3. Implementing Cross-Platform Deep Links
Follow this 3-step sequence (details and full code in references/deep-links.md):
- Register URI scheme per OS:
- Android:
AndroidManifest.xml<intent-filter>(or App Links) - iOS / macOS:
Info.plistCFBundleURLTypes(or Universal Links) - Windows: Registry / package manifest URI activation (avoid reserved schemes)
- Linux:
.desktopfile
- Android:
- Attach
deepLinkstocomposable<Route>:- Prefer type-safe
navDeepLink<Route>(basePath = ...)(required fields → path params; default-value & collection fields → query params) or explicitnavDeepLink { uriPattern = ... }. - Ensure URI patterns do not overlap across destinations.
- For Web, place parameters in URL fragments (
localhost:8080/#dlscreen%2F{name}).
- Prefer type-safe
- Bridge OS URI callbacks to
NavController:- Create
ExternalUriHandlersingleton incommonMainwith cold-start caching. - Forward Desktop (
Desktop.getDesktop().setOpenURIHandleron macOS, CLIargson Windows/Linux) and iOS (application(_:open:options:)) URIs toExternalUriHandler.onNewUri(...). - Bind
ExternalUriHandler.listener = { navController.navigate(NavUri(it)) }insideDisposableEffect(Unit)in the root composable.
- Create
4. Setting Up UI & Localization Tests
What are you testing?
├─ Shared Compose UI interactions / state / navigation
│ ├─ Add `org.jetbrains.compose.ui:ui-test` to `commonTest` and `compose.desktop.currentOs` to `jvmTest`
│ ├─ For Android emulator tests, wire `androidLibrary { withDeviceTestBuilder { sourceSetTreeName = "test" } }`,
│ │ `AndroidJUnitRunner`, `ui-test-junit4-android` + `ui-test-manifest`, and `androidDeviceTest/AndroidManifest.xml`
│ └─ Write `@Test fun ...() = runComposeUiTest { setContent { ... } }`
│ -> Read references/ui-testing.md
└─ Multi-locale strings, fallback resources, RTL/LTR, regional dates/numbers, multi-script (zh-Hans/zh-Hant)
├─ Android: `adb -e shell` `setprop persist.sys.locale ...;stop;sleep 5;start` or Espresso `LocaleTestRule()`
├─ iOS: XCUITest `app.launchArguments = ["-AppleLanguages", "(es)", "-AppleLocale", "es_ES"]`
├─ Desktop: `java.util.Locale.setDefault(...)` before UI init
└─ Web: browser prefs, Selenium/Puppeteer, or custom `window.navigator.languages`
-> Read references/localization-testing.md
Reference Files
Read only the reference file(s) relevant to the current task:
| Reference | When to read |
|---|---|
| references/lifecycle.md | Configuring lifecycle-runtime-compose, LifecycleOwner, desktop coroutines, or checking iOS/Web/Desktop lifecycle state mappings. |
| references/viewmodel.md | Wiring ViewModel in commonMain, Navigation 3 ViewModel decorators, Koin/Metro DI, or iOS SwiftUI KMP-ObservableViewModel integration. |
| references/navigation-2.md | Setting up NavHost/NavController, type-safe @Serializable routes, back stack ops, iOS/Desktop back gestures, or evaluating alternatives. |
| references/navigation-3.md | Setting up Navigation 3 (navigation3-ui), NavDisplay, adaptive navigation, and non-JVM polymorphic NavKey serialization patterns. |
| references/navigation-routing-web.md | Binding NavController to browser history (bindToBrowserNavigation), @SerialName URLs, custom # fragments, and reverse URL parsing in Wasm/JS. |
| references/deep-links.md | Registering OS URI schemes, configuring navDeepLink patterns, Web fragment deep links, and implementing ExternalUriHandler for iOS/Desktop. |
| references/ui-testing.md | Configuring ui-test dependencies, Android androidDeviceTest manifest/runner, writing runComposeUiTest tests, and target Gradle test commands. |
| references/localization-testing.md | Switching locales on Android/iOS/Desktop/Web and validating fallback resources, regional formats, RTL/LTR, and multi-script locales. |