[英]How to persist ViewModel when navigating in Android?
new to android, and doing it the Compose
way. android 的新手,并以
Compose
的方式进行。
I have a BottomNavigation
and three taps, each draw a different screen.我有一个
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)
}
Using the backbutton or just tapping through each viewModel of the different screens seems to re init
.使用后退按钮或只是点击不同屏幕的每个 viewModel 似乎重新
init
。 Is that the expected behavior?这是预期的行为吗? I like to persist the viewModel when switching routes.
我喜欢在切换路由时保留 viewModel。
I don't have fragments, just one activity with composable我没有片段,只有一个可组合的活动
TIA TIA
If you want to share viewModel instance across your Nav Graph and your host activity you can do 2 things如果你想在你的导航图和你的主机活动中共享 viewModel 实例,你可以做两件事
one is assigning the local ViewModelStoreOwner
一个是分配本地
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
}
}
}
or another approach is creating a Local composition of your Activity instance and set it up like this或者另一种方法是创建 Activity 实例的 Local 组合并像这样设置它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.