Learning Android Development
Injecting ViewModel with Dagger Hilt
No more Factory Needed for ViewModel with Dependencies
Published in
3 min readJul 1, 2020
ViewModel is one of the best things in Android Jetpack to enable logic moving away from Activity.
However, one big fall back the ViewModel has it, there’s no easily inject dependencies into it while having it injected into the Activity. I explore many ways as per this article, and none of them are ideal.
Thankfully now with Dagger Hilt, this is made so much more possible.
Recap on ViewModel (without injection)
Assuming I have to an Activity with its ViewModel. There are three things the Activity need to pass to the View Model
- The Dependencies the ViewModel needs, i.e. the Repository as per the diagram above.
- The SavedStateRegistryOwner. This will be used to hold the saved stated so that ViewModel can preserve saved stated
- The Bundle Intent, where Activity can pass its argument intent received over to ViewModel.