Skip to content

Recipe Request for Nav3 Shared ViewModel #169

@ngissac

Description

@ngissac

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    recipe-requestRequest for a recipe or an update to an existing recipe

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions