Dependency Injection on Android with Hilt

Translator’s note: I found this post today after seeing Hilt at the top of the official Jetpack front page

The following is the translation:

Dependency injection (DI) is a technique widely used for programming and ideally suited for Android development, where dependencies provide a class rather than creating their own. By following the DI principles, you will be laying the foundation for good application architecture, greater code reusability, and ease of testing. Have you ever tried manual dependency injection in your application? Even with many of today’s existing dependency injection libraries, as your project gets bigger, it still requires a lot of boilerplate code because you have to manually construct each class and its dependencies and create containers to reuse and manage the dependencies

By following the DI principles, you will be laying the foundation for good application architecture, greater code reusability, and ease of testing

Hilt

The new Hilt library defines a standard way to perform DI in your applications by providing a container for each Android class in your project and automatically managing its life cycle for you. Hilt is currently in Alpha, please try it out in your application and give us feedback using this link.

Hilt is built on the popular DI library Dagger and therefore benefits from the compile-time correctness, runtime performance, extensibility, and Android Studio support that Dagger provides. As a result, Dagger has an extensive adoption rate of 74% among the top 10K apps in the Google Play Store. However, because compile-time code is generated, you can expect the compile time to increase

Since many Android Framework classes are instantiated by the operating system itself, there is an associated template when using a Dagger in an Android application. Unlike Dagger, Hilt integrates with the Jetpack library and Android Framework classes and removes most of the boilerplate, allowing you to focus on defining and injecting important parts of the binding without having to worry about managing all the Dagger Settings and access. It automatically generates and provides:

  • A component that integrates the Android Framework class (without manually creating it) with the Dagger

  • Hilt automatically generates scoped annotations

  • Prebinding and qualification

Most importantly, since the Dagger and Hilt can coexist, the application can be migrated as needed

The use of the Hilt

To show you the ease of use of Hilt, let’s perform some quick DI in a typical Android application. Let’s have Hilt inject the AnalyticsAdapter into our MainActivity

First, enable Hilt in your application by annotating the application with @HiltAndroidApp to trigger code generation for Hilt

@HiltAndroidApp
class MyApplication : Application() {... }Copy the code

Then, tell Hilt how to provide an instance of AnalyticsAdapter by annotating its constructor with @inject

class AnalyticsAdapter @Inject constructor() {... }Copy the code

After that, to Inject the AnalyticsAdapter instance into MainActivity, enable Hilt in the activity with the @AndroidEntryPoint annotation and perform field injection with the @Inject annotation:

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
  @Inject lateinit var analytics: AnalyticsAdapter
  override fun onCreate(savedInstanceState: Bundle?). {
    super.onCreate(savedInstanceState)
    // The Analytics instance has been created by Hilt
    // And it can be used here}}Copy the code

For more information, you can easily check out the functionality of the new annotations in the cheat sheet section below

Jetpack support!

You can use your favorite Jetpack library out of the box

In this release, we provide direct injection support for ViewModel and WorkManager

For example, to inject the ViewModel component LoginViewModel into the LoginActivity, you can annotate the LoginViewModel with the @ViewModelInject annotation and use it in the Activity or Fragment

class LoginViewModel @ViewModelInject constructor(
  private val analyticsAdapter: AnalyticsAdapter
): ViewModel { ... }
@AndroidEntryPoint
class LoginActivity : AppCompatActivity() {
  private val loginViewModel: LoginViewModel by viewModels()
  override fun onCreate(savedInstanceState: Bundle?). {
    super.onCreate(savedInstanceState)
    // loginViewModel is available here}}Copy the code

Learn more about Jetpack support in the documentation

Start using Hilt

If you are interested in Hilt and want to learn more about it, you can learn it your way through the following resources:

Introduction to Hilt

Learn how to add Hilt to your Android application with this guide

The document

If you are not familiar with DI or Dagger before, check out the guide to adding Hilt to Android. If you already know Dagger, we will also provide documentation for Dagger. Dev

If you’re only interested in the new annotations and Hilt’s capabilities, check out the cheat sheet in the following section

For the Dagger user

If you already use Dagger or watcher.android in your application, check out this migration guide or Codelabs mentioned below to help you switch to Hilt. Since the Dagger and Hilt can coexist, you can migrate the application step by step

Codelabs

To learn Hilt step by step, we offer two Codelabs

  • Use Hilt in the Android App
  • Migration from Dagger to Hilt

The sample code

Would you like to see how Hilt is used in an existing application? Check its usage in the Dev-hilt branch of the Google I/O 2020 app and Android Architecture sample Github repository

feedback

Hilt is currently in Alpha, please try it out in your application and give us feedback using this link

Cheat sheet

This cheat sheet allows you to quickly understand the difference between Hilt and Dagger annotations and how to use them

Download cheat sheet in PDF

Thank you Florina Muntenescu and Nick Butcher

About me

I am Flywith24, and my blog content has been classified here. You can click Watch in the upper right corner to get updates of my articles in time, oh 😉

  • The Denver nuggets

  • Small column

  • Github