Hilt Introduction - Starting DI Hiltastic way

krisrajkumar

Dev Arena

Posted on May 21, 2021

Hilt Introduction - Starting DI Hiltastic way

Introduction

Hilt is an DI library for Android introduced by Google. Hilt is built on top of powerful Dagger library which leverages the benefits of Dagger like compile-time correctness, runtime performance, scalability and Android Support. Hilt has good integration with Jetpack Libraries like Compose, Navigation and WorkManager etc.

  • Hilt is Stable and Production ready.
  • Designed particularly for Android.
  • Supports from Android Studio 4.0.
  • Officially recommended DI library for Android.
  • Incorporates best practices of DI.
  • Hilt is just an API around Dagger but not new library.

Advantages

  1. Simplify the Dagger implementation.
  2. Reduces the boilerplate code.
  3. Decouples the build dependencies.
  4. Robust configurations for testing.
  5. Refactoring and Testing is Easy.

Annotations

Hilt and Dagger can work together. Most of the Dagger annotations are supported by Hilt. Hilt support for following Android specific classes.

  • Application
  • ViewModel
  • Activity
  • Fragment
  • View
  • Service
  • BroadcastReceiver

Alt Text

Components & Scopes

Hilt supports set of predefined Android lifecycle aware Components and Scopes. Lifetime of the components are usually bound during the creation and destruction of the corresponding instance. Below table shows the components and their scopes.
Alt Text

Setting Up

Adding Dependencies

Add the gradle plugin into the projects root level build.gradle.

buildscript {
    ...
    ext.hilt_version = '2.35'
    dependencies {
        ...
        classpath "com.google.dagger:hilt-android-gradle-plugin:$hilt_version"
    }
}
Enter fullscreen mode Exit fullscreen mode

Add the dependencies into app level app/build.gradle.

apply plugin: 'kotlin-kapt'
apply plugin: 'dagger.hilt.android.plugin'

android {
    ...
}

dependencies {
    implementation "com.google.dagger:hilt-android:$hilt_version"
    kapt "com.google.dagger:hilt-compiler:$hilt_version"
}

Enter fullscreen mode Exit fullscreen mode

Hilt uses Java 8 features. Hence, add the Java 8 support into app level app/build.gradle.

android {
  ...
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}
Enter fullscreen mode Exit fullscreen mode

Keep Watching :) Let's dive into the implementation part in next article.

💖 💪 🙅 🚩
krisrajkumar
Dev Arena

Posted on May 21, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related