Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between ViewModel that extends BaseObservable and Android ViewModel Class?

Tags:

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.

like image 459
Urvish rana Avatar asked May 10 '18 10:05

Urvish rana


People also ask

What is the difference between AndroidViewModel and ViewModel?

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.

What is an android ViewModel?

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).

What is ViewModel Observable?

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.

Do we have references of activity in ViewModel?

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 .


1 Answers

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.

like image 120
Mr.Q Avatar answered Sep 17 '22 12:09

Mr.Q