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

- 4,316
- 3
- 43
- 40
-
5"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. – Daniel Andujar May 09 '19 at 20:28
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)

- 1,184
- 1
- 11
- 22
-
I am bit confused about BaseObservale and SingleLiveEvent. Plz explain the both use cases – Ness Tyagi Aug 05 '19 at 17:54
-
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 baseobservable – Hans Jun 09 '21 at 09:23