Adding a ViewModel

Now, back to ViewModel. A ViewModel is related to one particular screen and is a great place to put logic involved in formatting the data to display on that screen. A ViewModel holds on to a model object and decorates the model – adding functionality to display onscreen that you might not want in the model itself. Using a ViewModel aggregates all the data the screen needs in one place, formats the data, and makes it easy to access the end result.

ViewModel is part of the androidx.lifecycle package, which contains lifecycle-related APIs including lifecycle-aware components. Lifecycle-aware components observe the lifecycle of some other component, such as an activity, and take the state of that lifecycle into account. ...

Get Android Programming: The Big Nerd Ranch Guide, 4th Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.