Quick start guide — Dagger-Hilt in Android app

Mohammed Audhil
2 min readJul 16, 2020

--

Dagger is a dependency injection library from Google, I’ll list improvements with successive library version releases till now, and my experiences with them

  1. Dagger — I’ve never used this library
  2. Dagger2 — was haunting at first, I became a master then.
  3. Dagger-Android(people developed to reduce boiler-plate coding!) — horrible + haunting — became intermediate!
  4. 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

courtesy: google.com

Step 0: Gradle dependencies,

app/build.gradle
build.gradle — project level

Step 1: annotate “@HiltAndroidApp” over the Application class,

NewsApplication.kt

Step 2: Module — provides class objects/instance in respective dependent classes,

retrofit2 — google for more info

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

world minimal dagger code :-)

Step 3: annotate “@AndroidEntryPoint” over the Activity, Fragment, Service, and @Inject required objects with ease!

“dummyClass” object injection at Activity

that's it! no more @Components, and other confusing setups.

Bonus,

Now ViewModel injection is made simple with just @ViewModelInject with the following dependency

app/build.gradle
minimal viewmodel class
viewmodel creation in Android Activity

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!

--

--

Mohammed Audhil

Software Engineer @Blackhawk_Networks | more: https://github.com/Audhil (Pray. Eat. Code. Sleep.)