Would I ever want an AndroidViewModel?

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:

  • I probably don’t want my motor to directly access Context (even less so Application). I’ll likely have a different class dealing with this that I inject into my motor (kind of how we use ToDoRepository which uses a ToDoDatabase which uses a Context).

  • If I do for some reason want a Context, I can just use DI to inject it (e.g. via viewModel { SomeMotor(androidContext()) }), so I wouldn’t need to use AndroidViewModel in this case.

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)?

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.

1 Like

Got it, that makes sense, thank you.