Introduction to Hilt in the MAD Skills series

<p><strong>This is the MAD Skills article series on Hilt!</strong>&nbsp;In this article we&rsquo;ll take a look at why dependency injection (DI) is important for your app and Hilt, Jetpack&rsquo;s recommended solution for DI on Android.</p> <p>If you prefer to consume this content in a video format, check it out here:</p> <p>&nbsp;</p> <p>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&nbsp;<a href="http://d.android.com/dependency-injection" rel="noopener ugc nofollow" target="_blank">here</a>.</p> <p>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.</p> <p>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&nbsp;<a href="https://github.com/google/iosched" rel="noopener ugc nofollow" target="_blank">iosched</a>, the open source Google I/O app. Can you imagine the amount of code required to create a&nbsp;<code><a href="https://github.com/google/iosched/blob/main/mobile/src/main/java/com/google/samples/apps/iosched/ui/feed/FeedViewModel.kt" rel="noopener ugc nofollow" target="_blank">FeedViewModel</a></code>&nbsp;with its dependencies and transitive dependencies?</p> <p>It&rsquo;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&rsquo;s where Hilt comes into play.</p> <h1>Hilt</h1> <p><a href="http://d.android.com/hilt" rel="noopener ugc nofollow" target="_blank">Hilt</a>&nbsp;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&rsquo;ve needed to write otherwise.</p> <p>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&nbsp;<a href="https://developer.android.com/training/dependency-injection/dagger-basics" rel="noopener ugc nofollow" target="_blank">Dagger</a>, the JVM DI library that Hilt is built on top of.</p> <p><a href="https://medium.com/androiddevelopers/introduction-to-hilt-in-the-mad-skills-series-40f0908f2fc0">Website</a></p>
Tags: MAD Skills