If you’re using Dagger as a dependency injection (DI) framework, chances are you’ve faced a situation where you couldn’t provide all dependencie

Assisted Injection for ViewModels in Android: Three Modern Approaches

submited by
Style Pass
2021-05-18 08:38:43

If you’re using Dagger as a dependency injection (DI) framework, chances are you’ve faced a situation where you couldn’t provide all dependencies.

To provide the repository dependency with Dagger, you’d end up with this (assuming the Repository is provided somewhere in a Module):

Now let’s assume you need an identifier to fetch a specific resource from your repository. You’d want to pass this identifier to the manager to let your injected repository query the wanted resource:

Since Dagger cannot provide this runtime parameter, you could extract it from the constructor and manually provide it by either:

Then you’d need to inject the Factory instead of the manager. Finally, you would use the create method to pass in the identifier:

As stated earlier, DI for ViewModel doesn’t work like with any other objects. Even though you could let Dagger provide your constructor parameters, you still need to use a ViewModelProvider to create one ViewModel instance.

The owner defines the ViewModel’s scope. Depending on it, the system will know whether to create a new ViewModel or retrieve an existing one satisfying the owner. Most of the time, it will be either an Activity or a Fragment.

Leave a Comment