Incorporating a ViewModel

The Jetpack has a class named ViewModel. Its name evokes GUI architecture patterns like Model-View-ViewModel (MVVM). In reality, ViewModel and its supporting classes are there to help us with a key challenge in Android: configuration changes.

A configuration change is any change in the device condition where Google thinks that we might want different resources. The most common configuration change is a change in the screen orientation, such as moving from portrait to landscape. We may want different layouts in this case, as our portrait layouts might be too tall for a landscape device, or our landscape layouts might be too wide for a portrait device.

Android’s default behavior when a configuration change occurs is to destroy all visible activities and recreate them from scratch, so you can load the desired resources. However, we need some means to hold onto information during this change, so our new activity has access to the same data that our old activity did. There are many solutions to this problem, but a ViewModel works fairly nicely, which is why we will use it here.

So, in this tutorial, we will set up a basic ViewModel for RosterListFragment.

You can learn more about ViewModel in the "Integrating ViewModel" chapter of Elements of Android Jetpack!

This is a continuation of the work we did in the previous tutorial. The book’s GitLab repository contains the results of the previous tutorial as well as the results of completing the work in this tutorial.

Step #1: Creating a Stub ViewModel

So, once again, we create a new Kotlin class. Right-click over the com.commonsware.todo package in the java/ directory and choose “New” > “Kotlin File/Class” from the context menu. For the name, fill in RosterMotor, then choose “Class” for the kind. Then press Enter or Return to create the empty RosterMotor class.

Then, modify RosterMotor to extend from ViewModel:

ppackage com.commonsware.todo

import androidx.lifecycle.ViewModel

class RosterMotor : ViewModel() {
}

Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.