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

The onCleared() function is called just before a ViewModel is destroyed. This is a useful place to perform any cleanup, such as un-observing a data source. For now, you simply log the fact that the ViewModel is about to be destroyed so that you can explore its lifecycle, the same way you explored the lifecycle of MainActivity in Chapter 3.

Now, open MainActivity.kt and associate the activity with an instance of QuizViewModel by invoking the viewModels() property delegate.

Listing 4.3  Accessing the ViewModel (MainActivity.kt)

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    private val quizViewModel: QuizViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        ...
        setContentView(binding.root)

        Log.d(TAG, "Got a QuizViewModel: $quizViewModel")

        binding.trueButton.setOnClickListener { view: View ->
            checkAnswer(true)
        }
        ...
    }
    ...
}

The by keyword indicates that a property is implemented using a property delegate. In Kotlin, a property delegate is, as the name suggests, a way to delegate the functionality of a property to an external unit of code. A very common property delegate in Kotlin is lazy. The lazy property delegate allows developers to save resources by waiting to initialize the property only when it is accessed.

The viewModels() property delegate works the same way: Your QuizViewModel will not be initialized unless you access it. By referencing it in a logging message, you can initialize it and log the value on the same line.

Under the hood, the viewModels() property delegate handles many things for you. When the activity queries for a QuizViewModel for the first time, viewModels() creates and returns a new QuizViewModel instance. When the activity queries for the QuizViewModel after a configuration change, the instance that was first created is returned. When the activity is finished (such as when the user closes the app from the overview screen), the ViewModelActivity pair is removed from memory.

You should not directly instantiate the QuizViewModel within your Activity. Instead, rely on the viewModels() property delegate. It might seem like instantiating the ViewModel yourself would work just the same, but you would lose the benefit of the same instance being returned after your Activity’s configuration change.

ViewModel lifecycle

You learned in Chapter 3 that activities transition between four states: resumed, started, created, and nonexistent. You also learned about different ways an activity can be destroyed: either by the user finishing the activity or by the system destroying it as a result of a configuration change.

When the user finishes an activity, they expect their UI state to be reset. When the user rotates an activity, they expect their UI state to be the same after rotation. ViewModel offers a way to keep an activity’s UI state data in memory across configuration changes. Its lifecycle mirrors the user’s expectations: It survives configuration changes and is destroyed only when its associated activity is finished.

When you associate a ViewModel instance with an activity’s lifecycle, as you did in Listing 4.3, the ViewModel is said to be scoped to that activity’s lifecycle. This means the ViewModel will remain in memory, regardless of the activity’s state, until the activity is finished. Once the activity is finished (such as by the user closing the app from the overview screen), the ViewModel instance is destroyed.

This means that the ViewModel stays in memory during a configuration change, such as rotation. During the configuration change, the activity instance is destroyed and re-created, but any ViewModels scoped to the activity stay in memory. This is depicted in Figure 4.1, using MainActivity and QuizViewModel.

Figure 4.1  MainActivity and QuizViewModel across rotation

MainActivity and QuizViewModel across rotation

To see this in action, run GeoQuiz. In Logcat, select Edit Filter Configuration in the dropdown to create a new filter. In the Log Tag box, enter QuizViewModel|MainActivity (the two class names with the pipe character | between them) to show only logs tagged with either class name. Name the filter ViewModelAndActivity (or another name that makes sense to you) and click OK (Figure 4.2).

Figure 4.2  Filtering QuizViewModel and MainActivity logs

Filtering QuizViewModel and MainActivity logs

Now look at the logs. When MainActivity first launches and logs the ViewModel in onCreate(…), a new QuizViewModel instance is created. This is reflected in the logs (Figure 4.3).

Figure 4.3  QuizViewModel instance created

QuizViewModel instance created

Rotate the device. The logs show the activity is destroyed (Figure 4.4). The QuizViewModel is not. When the new instance of MainActivity is created after rotation, it requests a QuizViewModel. Since the original QuizViewModel is still in memory, viewModels() returns that instance rather than creating a new one.

Figure 4.4  MainActivity is destroyed and re-created; QuizViewModel persists

MainActivity is destroyed and re-created; QuizViewModel persists

Finally, open the overview screen and close the application. QuizViewModel.onCleared() is called, indicating that the QuizViewModel instance is about to be destroyed, as the logs show (Figure 4.5). The QuizViewModel is destroyed, along with the MainActivity instance.

Figure 4.5  MainActivity and QuizViewModel destroyed

MainActivity and QuizViewModel destroyed

The relationship between MainActivity and QuizViewModel is unidirectional. The activity references the ViewModel, but the ViewModel does not access the activity. Your ViewModel should never hold a reference to an activity or a view, otherwise you will introduce a memory leak.

A memory leak occurs when one object holds a strong reference to another object that should be destroyed. The strong reference prevents the garbage collector from clearing the object from memory. Memory leaks due to a configuration change are common bugs. (The details of strong reference and garbage collection are outside the scope of this book. If you are not sure about these concepts, we recommend reading up on them in a Kotlin or Java reference.)

Your ViewModel instance stays in memory across rotation, while your original activity instance gets destroyed. If the ViewModel held a strong reference to the original activity instance, two problems would occur: First, the original activity instance would not be removed from memory, and thus the activity would be leaked. Second, the ViewModel would hold a reference to a stale activity. If the ViewModel tried to update the view of the stale activity, it would trigger an IllegalStateException.

Add data to your ViewModel

Now it is finally time to fix GeoQuiz’s rotation bug. QuizViewModel is not destroyed on rotation the way MainActivity is, so you can stash the activity’s UI state data in the QuizViewModel instance and it, too, will survive rotation.

You are going to cut the question and current index data from your activity and paste them in your ViewModel, along with all the logic related to them. Begin by cutting the currentIndex and questionBank properties from MainActivity (Listing 4.4).

Listing 4.4  Cutting model data from activity (MainActivity.kt)

class MainActivity : AppCompatActivity() {
    ...
    private val questionBank = listOf(
        Question(R.string.question_australia, true),
        Question(R.string.question_oceans, true),
        Question(R.string.question_mideast, false),
        Question(R.string.question_africa, false),
        Question(R.string.question_americas, true),
        Question(R.string.question_asia, true)
    )

    private var currentIndex = 0
    ...
}

Now, paste the currentIndex and questionBank properties into QuizViewModel, as shown in Listing 4.5. While you are editing QuizViewModel, delete the init and onCleared() logging, as you will not use them again.

Listing 4.5  Pasting model data into QuizViewModel (QuizViewModel.kt)

class QuizViewModel : ViewModel() {

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

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

    private val questionBank = listOf(
        Question(R.string.question_australia, true),
        Question(R.string.question_oceans, true),
        Question(R.string.question_mideast, false),
        Question(R.string.question_africa, false),
        Question(R.string.question_americas, true),
        Question(R.string.question_asia, true)
    )

    private var currentIndex = 0
}

Next, add a function to QuizViewModel to advance to the next question. Also, add computed properties to return the text and answer for the current question.

Listing 4.6  Adding business logic to QuizViewModel (QuizViewModel.kt)

class QuizViewModel : ViewModel() {

    private val questionBank = listOf(
       ...
    )

    private var currentIndex: Int = 0

    val currentQuestionAnswer: Boolean
        get() = questionBank[currentIndex].answer

    val currentQuestionText: Int
        get() = questionBank[currentIndex].textResId

    fun moveToNext() {
        currentIndex = (currentIndex + 1) % questionBank.size
    }
}

Earlier, we said that a ViewModel stores all the data that its associated screen needs, formats it, and makes it easy to access. This allows you to remove presentation logic code, such as the current index, from the activity – which in turn keeps your activity simpler. And keeping activities as simple as possible is a good thing: Any logic you put in your activity might be unintentionally affected by the activity’s lifecycle. Also, removing presentation logic means the activity is only responsible for handling what appears on the screen, not the logic behind determining the data to display.

Next, finish cleaning up MainActivity. You are ready to delete the old computation of currentIndex, and you will also make a couple other changes. Since you do not want to directly access MainActivity from within your ViewModel, you will leave the updateQuestion() and checkAnswer(Boolean)functions in MainActivity – but you will update them to call through to the new, smarter computed properties in QuizViewModel.

Listing 4.7  Updating question through QuizViewModel (MainActivity.kt)

class MainActivity : AppCompatActivity() {
    ...
    override fun onCreate(savedInstanceState: Bundle?) {
        ...
        binding.nextButton.setOnClickListener {
            currentIndex = (currentIndex + 1) % questionBank.size
            quizViewModel.moveToNext()
            updateQuestion()
        }
        ...
    }
    ...
    private fun updateQuestion() {
        val questionTextResId = questionBank[currentIndex].textResId
        val questionTextResId = quizViewModel.currentQuestionText
        binding.questionTextView.setText(questionTextResId)
    }

    private fun checkAnswer(userAnswer: Boolean) {
        val correctAnswer = questionBank[currentIndex].answer
        val correctAnswer = quizViewModel.currentQuestionAnswer
        ...
    }

Run GeoQuiz, press NEXT, and rotate the device or emulator. No matter how many times you rotate, the newly minted MainActivity will remember what question you were on. Do a happy dance to celebrate solving the UI state loss on rotation bug.

But do not dance too long. There is another, less easily discoverable bug to squash.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset