如何在Android导航时持久化ViewModel ?



android新手,用Compose的方式。

我有一个BottomNavigation和三个水龙头,每个画一个不同的屏幕。

@Composable
fun SetupNavigation(navHostController: NavHostController) {
NavHost(navController = navHostController, startDestination = "home") {
composable(route = "first") {
FirstScreen()
}
composable(route = "second") {
SecondScreen()
}
composable(route = "third") {
ThirdScreen()
}
}
}
@Composable
fun FirstScreen(
firstScreenViewModel: FirstScreenViewModel = hiltViewModel()
) {
val uiState by firstScreenViewModel.uiState.collectAsState()
Log.i("FirstScreen", "uiState: $uiState")
val coins = uiState.coinsList
ItemsList(items = items)
}

使用后退键或只是通过不同屏幕的每个viewModel点击似乎是init。这是预期行为吗?我喜欢在切换路由时持久化viewModel。

我没有fragment,只有一个activity with composable

TIA

如果你想在你的导航图和你的宿主活动中共享viewModel实例,你可以做两件事

一个是分配本地ViewModelStoreOwner

@Composable
fun SetupNavigation(navHostController: NavHostController) {
val viewModelStoreOwner = checkNotNull(LocalViewModelStoreOwner.current) {
"No ViewModelStoreOwner was provided via LocalViewModelStoreOwner"
}
NavHost(navController = navHostController, startDestination = "home") {
composable(route = "first") {
FirstScreen(firstScreenViewModel = hiltViewModel(viewModelStoreOwner))
}
composable(route = "second") {
SecondScreen() // you can also do it here if you want
}
composable(route = "third") {
ThirdScreen() // you can also do it here if you want
}
}
}

或者另一种方法是创建Activity实例的本地组合,并像这样设置

相关内容

  • 没有找到相关文章

最新更新