4

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 
      }
   }
}

2 Answers2

5

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.

Francesc
  • 25,014
  • 10
  • 66
  • 84
0

It is not explicitly supported in Android as far as I know. However, you could create a method named onViewModelCleared() inside the viewmodel itself and pass null to all the nullable objects, and something lightweight to non-null objects.

Richard Onslow Roper
  • 5,477
  • 2
  • 11
  • 42
  • 3
    This is entirely incorrect - the `NavHost` will automatically call the existing `onCleared()` method of every `ViewModel` created in a screen once that screen is popped off the back stack before removing that `ViewModel` from memory. – ianhanniballake Jul 12 '21 at 17:48
  • What I meant, was manual clearance. That is why I used the word "explicitly" – Richard Onslow Roper Jul 12 '21 at 19:16