Question around sharing VMs with hilt and compose ...
# compose
c
Question around sharing VMs with hilt and compose navigation having following navGraph
Copy code
NavHost(navController, startDestination = "home") {
    composable("home") {
        Home(/* uses viewModel by hiltViewModel() */) 
    }
    subGraph()
}

fun NavGraphBuilder.subGraph() {
	composable("subDestination") {
		MyComposable()
	}
}

fun MyComposable(
	viewModel by hiltViewModel(/* Home backstackEntry ?*/)
)
I want to share VM between the “Home” and the nested destination in the subgraph. I’m not passing down the navController to nested graphs to avoid dependencies to navigation in there. Is there a way I get the home backStackEntry for my nested destination still without quering it in place? Passing the entry down from top level does not work as when building the graph intially there is not yet a backStackEntry to query
for now i did quite a verbose solution: the nested destination looks as follows:
Copy code
@Composable
fun NestedDestinationComposable(
    backStackEntry: NavBackStackEntry,
    vm: MyViewModel = hiltViewModel(backStackEntry))
the nested navgraph has a callback to get the actual backStackEntry
Copy code
NavGraphBuilder.goalNavGraph(
    getSharedBackStackEntry: () -> NavBackStackEntry,) {
  composable() {
     NestedNavComposable(
        remember { getSharedBackStackEntry()}
     )
  }
}
the top level navgraph
Copy code
NavHost(
    navController,
    startDestination = "Home"
) {
    composable("Home") {
        HomeScreen()
    }
    subGraph(
        getSharedBackStackEntry = { navController.getBackStackEntry("Home") },
        ...
    )
}