Would I ever want an AndroidViewModel?

from the CommonsWare Community archives

At July 17, 2020, 1:00pm, fstanis asked:

I’ve been going through “Exploring Android” and I came across this:

There are two base classes that we can choose from: ViewModel and AndroidViewModel. The latter is for cases where we need a Context, that “god object” in Android that provides access to all sorts of Android-specific things.

However, as I progressed through the book, two things occurred:

Am I missing something here? Is there a good example where AndroidViewModel is better to use than a ViewModel with injected Context (or something else that uses a Context)?


At July 17, 2020, 1:16pm, mmurphy replied:

Google is not requiring DI.

If you have a project that is using DI, injecting the Context is a fine solution. I use that in my Koin examples. However, not everybody is using DI, and Google is providing AndroidViewModel for cases where you are not, yet still need access to resources or something from the viewmodel.


At July 20, 2020, 10:22pm, fstanis replied:

Got it, that makes sense, thank you.