Eug*_*sky 4 android android-jetpack android-jetpack-compose
In my project I have a splash screen, when it is displayed, my app loading some startup data from server, after loading the data shows another screen. For splash screen I create a ViewModel, but it stays in memory all the time. How to destroy it correctly?
Thank you for help!
@HiltViewModel
class SplashViewModel @Inject constructor (private val repository: Repository) {
....
}
Run Code Online (Sandbox Code Playgroud)
@Composable
fun SplashScreen(vm: SplashViewModel) {
...
}
Run Code Online (Sandbox Code Playgroud)
@Composable
fun Navigate() {
val navController = rememberNavController()
NavHost(navController = navController, startDestination = "splash") {
composable("splash") {
SplashScreen(vm = hiltViewModel())
}
composable("main") {
MainScreen(...) // When shows MainScreen, SplashViewModel object still is in memory
}
}
}
Run Code Online (Sandbox Code Playgroud)
您的视图模型保留在内存中,因为您的启动屏幕是您的根目的地,因此它始终作为底部条目保留在堆栈中。
如果您希望在离开启动屏幕时自动销毁启动视图模型,则应在导航到主屏幕时使用popUpTo.
您可以考虑的另一个选择是将主屏幕设为根目标,然后从该屏幕导航到启动应用程序(如果您是全新启动应用程序)。
像您一样使用hiltViewModel视图模型并将其范围限定到导航图目标将确保当用户离开该屏幕时视图模型被销毁(前提是它不在后台堆栈中)。
| 归档时间: |
|
| 查看次数: |
4746 次 |
| 最近记录: |