简体   繁体   中英

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

我目前正在研究MVVM架构模式,但我在扩展BaseObservable的Custom ViewModel类和Android本身提供的另一个ViewModel之间感到困惑。

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM