Integrating ViewModel

If you happened to install and run the RecyclerViewBasics sample app, try the following:

  1. Run the app
  2. Make note of the top color
  3. Rotate the device

Most likely, you will find that the top color is different than before. This implies that we generated a new random set of colors. And, if you keep switching the device between portrait and landscape, you would keep getting new colors.

That is not great.

It would be worse if our data were coming from disk, or from the network, instead of being randomly generated. If we have to re-load our data every time that the user rotates the screen, we would wind up having to make many extra requests of our database (local or remote), wasting time and battery.

In this chapter, we will focus on how to avoid this problem, through a viewmodel.

Configuration Changes

When you call methods in the Android SDK that load a resource (e.g., setContentView(R.layout.activity_main)), Android will walk through your resource sets, find the right resource for the given request, and use it.

But what happens if the configuration changes after we asked for the resource? For example, what if the user was holding their device in portrait mode, then rotates the screen to landscape? We might want a version of our layouts that can take advantage of the wider screen, if such versions exist. And, since we already requested the resources, Android has no good way of handing us revised resources on the fly… except by forcing us to re-request those resources. So, this is what Android does, by default, to our foreground activity, when the configuration changes on the fly.

The biggest thing that Android does on a configuration change is destroy and recreate our activity. In other words:

This may seem… invasive. You might not expect that Android would wipe out a perfectly good activity, just because the user flicked her wrist and rotated the screen of her phone. However, this is the only way Android has that guarantees that we will re-request all our resources.


Prev Table of Contents Next

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