这正是navigation graph scoped view models 的用途。
这涉及两个步骤:
-
找到与您希望将 ViewModel 范围限定为的图形关联的 NavBackStackEntry
-
将其传递给viewModel()。
对于第 1 部分),您有两个选择。如果您知道导航图的路线(通常您应该知道),您可以直接使用getBackStackEntry:
// Note that you must always use remember with getBackStackEntry
// as this ensures that the graph is always available, even while
// your destination is animated out after a popBackStack()
val navigationGraphEntry = remember {
navController.getBackStackEntry("graph_route")
}
val navigationGraphScopedViewModel = viewModel(navigationGraphEntry)
但是,如果您想要更通用的东西,您可以使用目标本身中的信息检索返回堆栈条目 - 它的 parent:
fun NavBackStackEntry.rememberParentEntry(): NavBackStackEntry {
// First, get the parent of the current destination
// This always exists since every destination in your graph has a parent
val parentId = navBackStackEntry.destination.parent!!.id
// Now get the NavBackStackEntry associated with the parent
// making sure to remember it
return remember {
navController.getBackStackEntry(parentId)
}
}
这允许您编写如下内容:
val parentEntry = it.rememberParentEntry()
val navigationGraphScopedViewModel = viewModel(parentEntry)
虽然parent 目标将等于简单导航图的根图,但当您使用nested navigation 时,父级是图的中间层之一:
NavHost(navController, startDestination = startRoute) {
...
navigation(startDestination = nestedStartRoute, route = nestedRoute) {
composable(route) {
// This instance will be the same
val parentViewModel: YourViewModel = viewModel(it.rememberParentEntry())
}
composable(route) {
// As this instance
val parentViewModel: YourViewModel = viewModel(it.rememberParentEntry())
}
}
navigation(startDestination = nestedStartRoute, route = secondNestedRoute) {
composable(route) {
// But this instance is different
val parentViewModel: YourViewModel = viewModel(it.rememberParentEntry())
}
}
composable(route) {
// This is also different (the parent is the root graph)
// but the root graph has the same scope as the whole NavHost
// so this isn't particularly helpful
val parentViewModel: YourViewModel = viewModel(it.rememberParentEntry())
}
...
}
请注意,您不仅限于直接父级:每个父级导航图都可用于提供更大的范围。