Jetpack组合导航-底部导航多个后端堆叠-查看模型范围问题 [英] Jetpack Compose Navigation - Bottom Nav Multiple Back Stack - View Model Scoping Issue

本文介绍了Jetpack组合导航-底部导航多个后端堆叠-查看模型范围问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有两个选项卡,选项卡A和选项卡B。每个选项卡都有自己的后端堆栈。我在google docs

中使用代码实现了多个后端堆栈导航
    val navController = rememberNavController()
Scaffold(
  bottomBar = {
    BottomNavigation {
      val navBackStackEntry by navController.currentBackStackEntryAsState()
      val currentDestination = navBackStackEntry?.destination
      items.forEach { screen ->
        BottomNavigationItem(
          icon = { Icon(Icons.Filled.Favorite, contentDescription = null) },
          label = { Text(stringResource(screen.resourceId)) },
          selected = currentDestination?.hierarchy?.any { it.route == screen.route } == true,
          onClick = {
            navController.navigate(screen.route) {
              // Pop up to the start destination of the graph to
              // avoid building up a large stack of destinations
              // on the back stack as users select items
              popUpTo(navController.graph.findStartDestination().id) {
                saveState = true
              }
              // Avoid multiple copies of the same destination when
              // reselecting the same item
              launchSingleTop = true
              // Restore state when reselecting a previously selected item
              restoreState = true
            }
          }
        )
      }
    }
  }
) { 
  NavHost(navController, startDestination = A1.route) {
    composable(A1.route) { 
       val viewModelA1 = hiltViewModel() 
       A1(viewModelA1) 
    }
    composable(A2.route) { 
       val viewModelA2 = hiltViewModel() 
       A2(viewModelA2) 
    }
    composable(A3.route) { 
       val viewModelA3 = hiltViewModel() 
       A3(viewModelA3) 
    }
  }
}
选项卡A有3个屏幕(屏幕A1->屏幕A2->屏幕A3)。我使用hiltViewModel()函数实例化视图模型,并在每个屏幕的composable()块中调用它

问题是当我从A1导航到A2再到A3,然后当我将Tab切换到Tab B时,屏幕A2的视图模型似乎正在被释放(onCleared被调用)。因此,当我返回到Tab A显示屏幕A3,然后返回到屏幕A2时,A2的视图模型再次实例化(再次调用init块)。我想要实现的是为该流保留A2的视图模型,直到我退出A2。

这可能吗?

推荐答案

找到了根本原因。我正在使用这些依赖项,但它们似乎不能配合使用。

androidx.hilt:hilt-navigation-compose:1.0.0-alpha03 

androidx.navigation:navigation-compose:2.4.0-alpha10" 

我删除了navigation:navigation-compose依赖项,现在它似乎工作正常。

这篇关于Jetpack组合导航-底部导航多个后端堆叠-查看模型范围问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆