ViewModel Pattern

What is a ViewModel?

The ViewModel is used to store and manage UI-related data while taking the UI controllers’ lifecycle into account. UI controllers can be activities or fragments.

What we mean by ViewModel being lifecycle aware is that it’s able to allow data to survive activity or fragment configuration changes, which may include changing screen orientation or pulling up the keyboard. Thanks to the ViewModel, data is retained to be used during configuration changes when an activity is destroyed and recreated so the user can still have the same data even when the screen orientation changes.

The ViewModel handles all of the logic for the activities and fragments, and the fragment’s job is simply to observe data and present it to the user, making it lightweight and easy to render in the layout. We’ll go through this in more detail in the next chapter.

The flowchart below depicts how the ViewModel controls the flow of data from the models to the view.

Get hands-on with 1200+ tech skills courses.