Learning Android Development

Injecting ViewModel with Dagger Hilt

No more Factory Needed for ViewModel with Dependencies

Picture by roegger on Pixabay

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

  1. The Dependencies the ViewModel needs, i.e. the Repository as per the diagram above.
  2. The SavedStateRegistryOwner. This will be used to hold the saved stated so that ViewModel can preserve saved stated
  3. The Bundle Intent, where Activity can pass its argument intent received over to ViewModel.

--

--