AndroidViewModel vs ViewModel

cascal picture cascal · May 24, 2017 · Viewed 42.3k times · Source

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?

Answer

Alex picture Alex · May 24, 2017

AndroidViewModel provides Application context

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

AndroidViewModel has application context. We all know having static context instance is evil as it can cause memory leaks!! However, having static Application instance is not as bad as you might think because there is only one Application instance in the running application.

Therefore, using and having Application instance in a specific class is not a problem in general. But, if an Application instance references them, it is a problem because of the reference cycle problem.

See Also about Application Instance

AndroidViewModel Problematic for unit tests

AVM provides application context which is problematic for unit testing. Unit tests should not deal with any of the Android lifecycle, such as context.