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
- Simplify the Dagger implementation.
- Reduces the boilerplate code.
- Decouples the build dependencies.
- Robust configurations for testing.
- 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
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.
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"
}
}
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"
}
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
}
}
Keep Watching :) Let's dive into the implementation part in next article.
Top comments (0)