Having a ViewModel in your application is a great way to retain data without prefetching it. This allows you to perform data retrieval from a database, db call, or API. A ViewModel is also useful for facilitating communication between UI components. A ViewModel can be used to share data between fragments and also to manage the state of the UI. It can also be used to communicate with background resources.
A ViewModel is one of the core components of a lifecycle-based app. The lifecycle of a ViewModel includes the initial creation of the associated UI controller, UI state retention, and UI state recovery. The lifecycle of a ViewModel can be extended by using a LiveData object to hold specific types of data. It also allows you to retrieve data using an API call, db call, or even a string from a bundle.
It is also a good idea to consider using the ViewModel in conjunction with a disk persistence technique, such as using a DB call, because it helps to preserve the UI’s state while the component is being recreated. Another feature of the ViewModel is that it allows you to persist the state of the UI during configuration changes. This is useful in scenarios where the UI is reused frequently. The ViewModel is not always a good choice when there is transient data to be displayed.
The onSaveInstance method is a standard feature of the ViewModel and should be implemented to keep your data safe. The lifecycle of a ViewModel is not as long as that of a UI controller, but you can still use the ViewModel to keep the UI state alive for a configurable period of time. A ViewModel can also be used as a communication medium between fragments and resources, such as using MvxMessenger. This allows you to send subscription change messages to other UI components. This is useful when you want to use a ViewModel in conjunction with a background resource such as a background service.
The viewmodel lifecycle also includes the creation of an Observer. An Observer is a special class that provides the view model with the capability to notify it of changes in its data. The Observer will use the onChange method to notify its data of changes. This method also updates its cached data in the Adapter. It is also a good idea to use the Observer to detect events such as changes in UI state, UI controllers, or other changes in the UI hierarchy.
Another way to test the view model lifecycle is to implement the onSaveState method. This is one of the best ways to ensure that you are saving the data you require when a configuration change occurs. This will allow you to use the data when you need it, and will also provide a backup should you die on your feet.
The ViewModel lifecycle can also be a good idea when you have a complex UI that has repetitive API calls. For example, a simple example is using a News object inside of a NewsViewModel. This allows you to observe the state of the news item without having to use the onSaveInstance method every time you need it.