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 “viewmodel” represents a collection of data and other state, necessary to render a view, derived from the underlying models. The viewmodel 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).

Ideally, the viewmodel 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 on its own. 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.


Prev Table of Contents Next

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