Introduction to Hilt in the MAD Skills series

This is the MAD Skills article series on Hilt! In this article we’ll take a look at why dependency injection (DI) is important for your app and Hilt, Jetpack’s recommended solution for DI on Android.

If you prefer to consume this content in a video format, check it out here:

 

By following the principles of dependency injection in your Android app, you lay the groundwork for a good app architecture. It helps with reusability of code, ease of refactoring and ease of testing! Learn more about DI benefits here.

When creating instances of classes in your project, you can exercise the dependency graph manually by satisfying the dependencies and transitive dependencies that the class requires.

But doing this manually every time involves some boilerplate code and could be error-prone. See for example, one of the ViewModels that we have in iosched, the open source Google I/O app. Can you imagine the amount of code required to create a FeedViewModel with its dependencies and transitive dependencies?

It’s hard, repetitive, and we could easily get the dependencies wrong. By using a dependency injection library, we can get the benefits of DI without having to provide the dependencies manually, as the library generates all the necessary code for you. And here’s where Hilt comes into play.

Hilt

Hilt is a dependency injection library developed by Google that helps you get the most out of DI best practices in your app by doing the hard work and generating all the boilerplate you would’ve needed to write otherwise.

By using annotations, Hilt generates that code for you at compile time, making it really fast at runtime. This is done using the power of Dagger, the JVM DI library that Hilt is built on top of.

Website

Tags: MAD Skills