Exploring ViewModel
The ViewModel
component is responsible for holding and processing data required by the 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.
ViewModel
components 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 be garbage collected when it is no longer necessary. The only method ViewModel
has is onCleared()
, which is called when ViewModel
terminates. You can use this method to terminate ongoing tasks and deallocate resources that will no longer be required.
Migrating data processing from 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 that your...