Would I ever want an AndroidViewModel?
from the CommonsWare Community archivesAt 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:
ViewModelandAndroidViewModel. The latter is for cases where we need aContext, 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 soApplication). I’ll likely have a different class dealing with this that I inject into my motor (kind of how we useToDoRepositorywhich uses aToDoDatabasewhich uses aContext). -
If I do for some reason want a
Context, I can just use DI to inject it (e.g. viaviewModel { SomeMotor(androidContext()) }), so I wouldn’t need to useAndroidViewModelin 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)?
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.