ViewModel
The ViewModel
component is responsible for holding and processing data required by the user interface (UI). It has the benefit of surviving configuration changes that destroy and recreate fragments and activities, which allows it to retain the data that can then be used to re-populate the UI.
It will eventually be destroyed when the activity or fragment is destroyed without being recreated or when the application process is terminated. This allows ViewModel
to serve its responsibility and to have garbage collected when it is no longer necessary. The only method ViewModel
has is the onCleared()
method, which is called when ViewModel
terminates. You can overwrite this method to terminate ongoing tasks and deallocate resources that will no longer be required.
Migrating data processing from the activities into ViewModel
helps create better and faster unit tests. Testing an activity requires an Android test to be executed on a device. Activities also have states, which means...