Mastering Hilt - Android | Kotlin | Hilt (Dagger 2) [Part 3]
Becoming Proficient in Dependency Injection with Hilt for Android (Kotlin)
Table of contents
Providing Dependencies with Hilt
Singleton Binding
Provides Annotation
Binds Annotation
Singleton Binding:
The @Singleton
annotation is used in Hilt to mark a class as a singleton, ensuring that only one instance of that class is created and shared across the entire application.
Example:
@Singleton
class MySingletonClass @Inject constructor() {
init {
// Initialization code
}
}
In this example, the MySingletonClass
is marked with @Singleton
, making it a singleton class. Hilt will ensure that there is only one instance of MySingletonClass
throughout the application
's lifecycle. Anytime this class is injected into other classes, they will receive the same instance.
Provides Annotation:
The @Provides
annotation is used in Hilt to define how to create and provide instances of specific classes or interfaces. This is typically used within a Hilt module.
Example:
@Module
@InstallIn(SingletonComponent::class)
object MyModule {
@Singleton
@Provides
fun provideMyDependency(): MyDependency {
return MyDependencyImpl()
}
}
In this example, MyModule
is a Hilt module that provides a dependency called MyDependency
. The @Provides
annotation indicates that this function will provide an instance of MyDependency
. When any class requests an instance of MyDependency
, Hilt will use this function to create and provide it.
Binds Annotation:
The @Binds
annotation is used in Hilt to tell the framework how to provide an implementation for an interface or an abstract class. This is typically used within a Hilt module.
Example:
@Module
@InstallIn(SingletonComponent::class)
abstract class MyModule {
@Singleton
@Binds
abstract fun bindMyDependency(impl: MyDependencyImpl): MyDependency
}
In this example, MyModule
is a Hilt module that provides a binding for the MyDependency
interface. The @Binds
annotation tells Hilt that when an instance of MyDependency
is requested, it should use MyDependencyImpl
as the concrete implementation.
These are the three common methods to provide dependencies with Hilt. We can choose the appropriate method based on the scenario and your project's needs. Hilt will automatically handle the dependency injection for us based on these annotations and configurations.