Should we use viewmodel and what benefits it brings?
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
- ViewModel objects are designed to outlive specific instantiations of views or LifecycleOwners. This design also means you can write tests to cover a ViewModel more easily as it doesn't know about view and Lifecycle objects.
- ViewModel objects are scoped to the Lifecycle passed to the ViewModelProvider when getting the ViewModel. The ViewModel remains in memory until the Lifecycle it's scoped to goes away permanently: in the case of an activity, when it finishes, while in the case of a fragment, when it's detached./li>
- If the ViewModel class is of type AndroidViewModel, then it will create a new instance passing the Application instance as a single parameter in the constructor.
Additional ViewModel benefits
ViewModels and onSaveInstanceState() address UI data in very different ways. onSaveInstanceState() is a lifecycle callback, whereas ViewModels fundamentally change the way UI data is managed in your app. Here are a few more thoughts on the benefits of using ViewModel in addition to onSaveInstanceState():
ViewModels encourage good architectural design. Your data is separated from your UI code, which makes the code more modular and simplifies testing.
onSaveInstanceState() is designed to save a small amount of transient data, but not complex lists of objects or media data. A ViewModel can delegate the loading of complex data and also act as temporary storage once this data is loaded.
onSaveInstanceState() is called during configuration changes and when the activity goes into the background; in both of these cases you actually do not need to reload or process the data if you keep it in a ViewModel.
Comments
Post a Comment