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) {
....
}
@Composable
fun SplashScreen(vm: SplashViewModel) {
...
}
@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
}
}
}
Your viewmodel stays in memory because your splash screen is your root destination, and as such it stays always on the stack as the bottom entry.
If you want your splash viewmodel to be automatically destroyed when you leave your splash screen you should pop it from the backstack when you navigate to your main screen, using popUpTo
.
Another option you could consider is to make your main screen the root destination and then navigate from that screen to splash if you are starting the app fresh.
Using hiltViewModel
and scoping the viewmodel to the nav graph destination as you do will ensure the viewmodel is destroyed when the user leaves that screen, provided it's not in the backstack.