I've a question regarding scoping of viewmodel acr...
# compose
i
I've a question regarding scoping of viewmodel across screens
Copy code
NavHost(
    navController = navController,
    startDestination = startDestination
) {

    composable(AppDestinations.SCREEN1_ROUTE) {
        val sampleViewModel = navController.hiltNavGraphViewModel<SampleViewModel>(AppDestinations.SCREEN1_ROUTE)
        ScreenOne(sampleViewModel = sampleViewModel, onClickHobby = actions.onClickDetail)
    }
    composable(AppDestinations.SCREEN2_ROUTE){
        val sampleViewModel = navController.hiltNavGraphViewModel<SampleViewModel>(AppDestinations.SCREEN1_ROUTE)
        ScreenTwo(sampleViewModel = sampleViewModel, onCompleteDetail = actions.onCompleteDetail)
    }
}
In the code snippet above, SampleViewModel needs to be shared between screen1 and screen2. With the above approach by passing the same route, screen1 and screen2 gets the same Sampleviewmodel instance. Is it the correct approach.
In the documentation, I saw this option of passing route to hiltNavGraphViewModel to get the viewmodel instance in a nested graph.
i
You can use a route of any destination on the back stack, so, yep, this is totally valid, but tightly couples these two destinations together, which may or may not be what you want
You could also use the
hiltNavGraphViewModel(navController.previousBackStackEntry!!)
if you're trying to use ViewModels to share information between two back to back fragments
Kind of a similar approach that Navigation allows for returning a result: https://developer.android.com/guide/navigation/navigation-programmatic#returning_a_result
i
Thanks Ian !! I don't want the destinations to be tightly coupled. I will go thru the approaches you've mentioned