I am currently studying about MVVM architectural pattern but I got confused between Custom ViewModel class that Extends BaseObservable and Another ViewModel which is provided by Android itself.
AndroidViewModel inherits ViewModel, so it has all the same functionality. The only added functionality for AndroidViewModel is that it is context aware: when initializing AndroidViewModel you have to pass the context as a parameter. This can be used if you want to show toasts for example.
AndroidViewModel. Application context aware ViewModel . ViewModel is a class that is responsible for preparing and managing the data for an Activity or a Fragment . It also handles the communication of the Activity / Fragment with the rest of the application (e.g. calling the business logic classes).
Using a ViewModel component that implements Observable gives you more control over the binding adapters in your app. For example, this pattern gives you more control over the notifications when data changes, it also allows you to specify a custom method to set the value of an attribute in two-way data binding.
Caution: A ViewModel must never reference a view, Lifecycle , or any class that may hold a reference to the activity context. ViewModel objects are designed to outlive specific instantiations of views or LifecycleOwners .
Your custom ViewModel is simply a data holder for your view and because it is bound to your view (and because it is an Observable object) it can notify the view about the changes in data. However, it is not aware of configuration changes such as orientation change (view rotation), therefore, in such cases, the programmer should save and restore data example here.
On the other hand, the ViewModel which is provided by Android is aware of these configuration changes and therefore its data is consistent throughout the activity lifecycle. The ViewModel will be destroyed when the activity destroys.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With