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


ViewModel

Many Android apps are trivial. The smaller the app, the less likely it is that you need much in the way of a true GUI architecture. Slapping together whatever you want wherever you want it most likely will suffice. Your average soundboard, flashlight, front-facing-camera “mirror”, and similar apps just do what they do, and their developers do not need to worry about the alphabet soup of MVC, MVP, MVVM, MVI, and so on.

If you are reading this book, you may have an app in mind that is not so trivial.

The more complex the app, the more likely it is that you are going to want to think more seriously about the GUI architecture. The Architecture Components contribution to this is the ViewModel, which we will explore in this chapter.

ViewModels, As Originally Envisioned

Microsoft devised the model-view-viewmodel (MVVM) GUI architecture in 2005, and it has remained generally murky ever since. This is not terribly surprising, as many of the “alphabet soup” GUI architectures have malleable definitions which developers can twist and tweak to match what it is that they want to write.

Roughly speaking, in this GUI architecture, the “view model” represents a collection of data and other state, necessary to render a view, derived from the underlying models. The view model would be responsible for things like data formatting (e.g., converting the model’s long Unix epoch time into something that the user will be able to read). The view updates the view model, which in turn updates the model at the appropriate time.

Ideally, the view model knows nothing much about the view, but rather just exposes data and operations that the view needs.

The Architecture Components ships with a ViewModel class. This class does almost nothing. This will be an important point, as what little we get from ViewModel can be implemented in other ways without significant difficulty. But, for now, consider ViewModel to be a place to hold the data necessary to represent your views. For example, a ViewModel might hold a list of objects, obtained from Room, that are used to populate a RecyclerView.

ViewModel Versus…

The preview of this section is in an invisible, microscopic font.

Dependencies

The preview of this section is in an invisible, microscopic font.

Mommy, Where Do ViewModels Come From?

The preview of this section was fed to a gremlin, after midnight.

ViewModels, Google’s Way

The preview of this section was traded for a bag of magic beans.

ViewModels as Simple POJOs

The preview of this section is [REDACTED].

ViewModels and Scopes

The preview of this section apparently resembled a Pokémon.