AndroidViewModel vs ViewModel

2019-01-16 09:24发布

问题:

With the introduction of the Android Architecture Components library, several new classes were introduced, including AndroidViewModel and ViewModel. However, I'm having trouble figuring out the difference between these two classes. The documentation succinctly describes AndroidViewModel as follows:

Application context aware ViewModel

I appreciate the brevity, but what exactly does this imply? When should we choose to use AndroidViewModel over ViewModel and vice-versa?

回答1:

If you need to use context inside your viewmodel you should use AndroidViewModel, because it contains the application context (to retrieve the context call getApplication() ), otherwise use regular ViewModel.