-
Notifications
You must be signed in to change notification settings - Fork 111
Description
Thank you for your excellent work on providing many recipes for the Android Navigation 3 library. I truly appreciate the effort you’ve put into helping the community.
However, I am facing some difficulties migrating from Jetpack Compose Navigation to Navigation 3. My existing code relies on sharedViewModel, which uses ViewModelStoreOwner to share a common ViewModel. Here is a sample of my current implementation:
@Composable
inline fun <reified T : ViewModel> NavBackStackEntry.sharedViewModel(
navController: NavController
): T {
val navGraphRoute = destination.parent?.route ?: return hiltViewModel()
val parentEntry = remember(this) {
navController.getBackStackEntry(navGraphRoute)
}
return hiltViewModel(parentEntry)
}
In Navigation 3, there is no longer a nav graph structure like:
navigation<Parent> {
composable<Child1> {
val viewModel = it.sharedViewModel<MyViewModel>(navController)
....
}
}
And here is my navigation module.
class MyNavigationModule @Inject constructor() :
BaseNavigationModule(),
Serializable {
override fun registerNavigation(
navGraphBuilder: NavGraphBuilder,
navController: NavHostController,
) {
navGraphBuilder.registerNavigation(navController)
}
private fun NavGraphBuilder.registerNavigation(
navController: NavHostController
) {
navigation<Parent> {
composable<Child1> {
val viewModel = it.sharedViewModel<MyViewModel>(navController)
....
}
}
Because of this, I am finding it difficult to migrate my existing setup to Navigation 3. Could you please provide a recipe or guidance on how to achieve a similar shared ViewModel pattern in Navigation 3?
Expected Outcome:
I would like to achieve a way to share a single ViewModel instance across multiple destinations in Navigation 3, similar to how sharedViewModel worked with Jetpack Compose Navigation. A recipe or guidance on the recommended approach would be very helpful.