Mastering Hilt - Android | Kotlin | Hilt (Dagger 2) [Part 5]

Mastering Hilt - Android | Kotlin | Hilt (Dagger 2) [Part 5]

Becoming Proficient in Dependency Injection with Hilt for Android (Kotlin)

ยท

2 min read

Scopes and Custom Scopes in Hilt

  • Singleton Scope

  • Custom Scope

Singleton Scope:

In Hilt, the @Singleton annotation is used to mark a class or a dependency as a singleton, ensuring that only one instance of that class is created and shared throughout the entire application lifecycle.

Example - Using @Singleton annotation:

@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 across the entire application. Anytime this class is injected into other classes, they will receive the same instance.

Custom Scopes:

Hilt allows us to define custom scopes to create more fine-grained control over the lifecycle of your dependencies. We can create your custom annotations and apply them to dependencies that need to be shared within a particular scope.

Example - Creating and using a custom scope:

@Scope
@Retention(AnnotationRetention.RUNTIME)
annotation class CustomScope

@CustomScope
class MyCustomScopedClass @Inject constructor() {
    init {
        // Initialization code
        }
}

In this example, we define a custom scope called CustomScope using the @Scope annotation. Then, we apply this custom scope to the MyCustomScopedClass using the @CustomScope annotation. When a class is annotated with @CustomScope, Hilt ensures that there is only one instance of that class within that scope.

To use the custom scope in a Hilt module:

@Module
@InstallIn(SingletonComponent::class)
object MyModule {
    @CustomScope
    @Provides
    fun provideCustomScopedClass(): MyCustomScopedClass {
        return MyCustomScopedClass()
        }
}

In this module, we provide an instance of MyCustomScopedClass with the @CustomScope annotation. This ensures that the dependency will be created and shared within the custom scope defined by CustomScope.

By using custom scopes, we can have more control over how long a dependency should live and when it should be re-created. This can be useful when we need to share a dependency within a specific section of your app, like a specific activityor fragment, without making it a singleton for the entire application.

ย