Member-only story
How ViewModels Work on Android
Learn how to use a ViewModel and how it works internally

According to Android’s documentation:
“Android architecture components are a collection of libraries that help you to build robust, testable, and maintainable apps.”
Android architecture components have many things, including classes for “managing your UI component lifecycle and handling data persistence,” as the docs say. In this piece, let’s learn about ViewModel
and its usages.
Introduction
ViewModel
is a class that’s responsible for preparing and managing the data for a UI component (an activity or a fragment). It also provides an easy way for communication between the activity and the fragment or between different fragments.
ViewModel
is always created in association with a scope (a fragment or an activity) and will be retained as long as the scope is alive — i.e.., if it’s an activity until it’s finished. In other words, this means a ViewModel
won’t be destroyed if its owner is destroyed for a configuration change (e.g., a rotation). The new instance of the owner will just reconnect to the existing ViewModel
. Lets’s see how this happens

The purpose of the ViewModel
is to acquire and keep the information that’s necessary for an activity or a fragment. The activity or the fragment should be able to observe changes in the ViewModel
. ViewModel
s usually expose this information via LiveData or Android Data Binding.
ViewModel
’s only responsibility is to manage the data for the UI. It should never access your view hierarchy or hold a reference back to the activity or the fragment.
Let’s first understand the benefits of using ViewModel
.
Benefits
ViewModel
survives rotation and other configuration changes.
2. ViewModel
keeps running while the activity is on the back stack.
3. ViewModel
is lifecycle-aware.