The Curious Case of Survival of Android ViewModel
If you are reading this article, then you must have some idea about ViewModels. ViewModels are the latest building blocks of an android app.
According to the official documentation:
The
ViewModel
class is designed to store and manage UI-related data in a lifecycle conscious way. TheViewModel
class allows data to survive configuration changes such as screen rotations.Architecture Components provides
ViewModel
helper class for the UI controller that is responsible for preparing data for the UI.ViewModel
objects are automatically retained during configuration changes so that data they hold is immediately available to the next activity or fragment instance.
FYI: You can use ViewModel
to preserve UI state only during a configuration change, nothing else as explained perfectly in this official doc. This image summarizes this doc perfectly.
After reading all this I assumed that, OK, then this is how ViewModel
works and preserve data during configuration change :
ViewModel
is a separate class which has an instance of it in the activity and has no reference forview
in it.