Christoph Wiesner
08/12/2022, 8:12 AMNavHost(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@Composable
fun NestedDestinationComposable(
backStackEntry: NavBackStackEntry,
vm: MyViewModel = hiltViewModel(backStackEntry))
the nested navgraph has a callback to get the actual backStackEntry
NavGraphBuilder.goalNavGraph(
getSharedBackStackEntry: () -> NavBackStackEntry,) {
composable() {
NestedNavComposable(
remember { getSharedBackStackEntry()}
)
}
}
the top level navgraph
NavHost(
navController,
startDestination = "Home"
) {
composable("Home") {
HomeScreen()
}
subGraph(
getSharedBackStackEntry = { navController.getBackStackEntry("Home") },
...
)
}