Quick start guide — Dagger-Hilt in Android app
Dagger is a dependency injection library from Google, I’ll list improvements with successive library version releases till now, and my experiences with them
- Dagger — I’ve never used this library
- Dagger2 — was haunting at first, I became a master then.
- Dagger-Android(people developed to reduce boiler-plate coding!) — horrible + haunting — became intermediate!
- Dagger-Hilt — looks good — it’s a piece of cake!
I’ll share steps, considering the reader has prior android app development, dagger2 dependency lib experiences
Step 0: Gradle dependencies,
Step 1: annotate “@HiltAndroidApp” over the Application class,
Step 2: Module — provides class objects/instance in respective dependent classes,
points to note,
@InstallIn — tells where these instances can be injected, and their lifetime
ApplicationComponent — represents Application, ActivityComponent — represents Activity, FragmentComponent — represents Fragment, ServiceComponent — represents Service.
dagger can also create an instance of classes whose constructors annotated with @Inject
Step 3: annotate “@AndroidEntryPoint” over the Activity, Fragment, Service, and @Inject required objects with ease!
that's it! no more @Components, and other confusing setups.
Bonus,
Now ViewModel injection is made simple with just @ViewModelInject with the following dependency
Conclusion,
annotations such as @HiltAndroidApp, @InstallIn, @AndroidEntryPoint, @ViewModelInject etc., generates needed components and other src code, no need to create @Components ourselves. I didn’t touch @Qualifier, @Scope to keep the guide simple.
A demo project is available at github
Happy Coding!