Adding a ViewModel

You are ready to create your ViewModel subclass, QuizViewModel. In the project tool window, right-click the com.bignerdranch.android.geoquiz package and select NewKotlin Class/File. Enter QuizViewModel for the name and double-click Class in the list of options below.

In QuizViewModel.kt, add an init block and override onCleared(). Log the creation and destruction of the QuizViewModel instance, as shown in Listing 4.2.

Listing 4.2  Creating a ViewModel class (QuizViewModel.kt)

private const val TAG = "QuizViewModel"

class QuizViewModel : ViewModel() {

    init {
        Log.d(TAG, "ViewModel instance created")
    }

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

Get Android Programming: The Big Nerd Ranch Guide, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.