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.
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.
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)
© 2022 - 2024 — McMap. All rights reserved.