The following is the first few sections of a chapter from Exploring Android, plus headings for the remaining major sections, to give you an idea about the content of the chapter.

Stubbing a ViewModel

The Architecture Components library 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 — the chapter on resource sets and configurations in The Busy Coder’s Guide to Android Development covers many of the classic approaches. ViewModel is a newcomer, but it works fairly nicely, which is why we will use it here.

So, in this tutorial, we will set up a basic ViewModel and make it available to our fragments. In the next tutorial, we will work on tying our ViewModel and that ViewState class together, so our ViewModel delivers updated ViewState instances to our UI for rendering.

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

Read Me!

Coverage of ViewModel from the Architecture Components can be found in:

Step #1: Adding the Dependency

The preview of this section was lost due to a rupture in the space-time continuum.

Step #2: Creating a Stub ViewModel

The preview of this section left for Hollywood to appear in a reality TV show.

Step #3: Lazy-Creating the ViewModel

The preview of this section is [REDACTED].

What We Changed

The preview of this section is [REDACTED].