ViewModel onCleared() not being run as shown in Figure 4.7

I’m working from the 4th edition as available on learning.oreilly.com

In chapter 4 we add a ViewModel to the application. When we first do so, we add an override on onCleared in QuizViewModel that is supposed to log when the application is being finished.

override fun onCleared() {
    super.onCleared();
    Log.d(TAG, "ViewModel instance about to be destroyed")
}

This code in MainActivity.kt brings the ViewModel into the app:

val provider: ViewModelProvider = ViewModelProviders.of(this)
val quizViewModel = provider.get(QuizViewModel::class.java)
Log.d(TAG, "Got a QuizVieModel: $quizViewModel")

So far as I know this is all the code needed to get the ViewModel in place.

This all works fine when starting and rotating the app, but the book states that when the application is finished (i.e. back button hit or app closed via the overview screen) I should see the log message we added onCleared() (this is shown in Figure 4.7). But I never see the log in onCleared() execute, no matter how I try to finish it.

I’ve double checked what I have entered in my app and I don’t think I have missed anything related to ViewModels. Has something changed in the way ViewModels behave?

FYI, this is being run on a physical device, a Samsung SM-J727U, if that makes any difference.

This is working for me as is on a Nexus 6. Are you seeing the MainActivity onPause(), onStop(), and onDestroy() logs?

One thing to try is to go in to the Developer Options and turn on “Don’t keep activities”.

On a second pass of reading this chapter, Listing 4.6 has you remove all the logging. Did you take them out?