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

2

28

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.

Profluent answered 10/5, 2018 at 10:14 Comment(0)
W
9

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.

Whitney answered 29/9, 2018 at 9:41 Comment(1)
"the ViewModel will be destroyed when the activity destroys." this is technically incorrect, the main idea behind the ViewModel is to persist configuration changes. that's the reason a ViewModelProvider is used instead of a direct construction in the onCreate.Alfrediaalfredo
A
2

The main difference between ViewModel() superclass and AndroidViewModel() superclass is that AndroidViewModel() has a reference to the application's context (not the activity context itself).

Activities are supposed to be destroyed and re-created when configuration changes (like rotating the phone). so its a bad idea to pass a context to the ViewModel, because it tends to Memory Leaks (reference to destroyed activities).

The ViewModel is intended to survive to these configuration changes, but the ViewModel() does not have any reference to Context.

the AndroidViewModel() on the other hand has a reference of the Application (a special type of Context) so you can access application specific information like packageManager.

class MyViewModel(application: Application) : AndroidViewModel(application)
Alfrediaalfredo answered 9/5, 2019 at 20:26 Comment(2)
I am bit confused about BaseObservale and SingleLiveEvent. Plz explain the both use casesHammon
This answer has nothing to do with the question. It is about the difference between a ViewModel and the AndroidViewModel. The question is about the diff between the viewmodel and the baseobservableSchutz

© 2022 - 2024 — McMap. All rights reserved.