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

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

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

ยท

2 min read

Component Dependencies in Hilt

Component dependencies in Hilt allow you to have multiple Hilt components that depend on each other. This feature is useful when you want to share dependencies between different components or create separate scopes for different parts of your application.

To demonstrate component dependencies, we'll create two components: AppComponent and SubComponent. The SubComponent will depend on the AppComponent and inherit its dependencies.

Example - Creating component dependencies in Hilt:

1. Define the AppComponent and SubComponent:

// Define a class that will be injected
class MyDependency @Inject constructor() {
    fun doSomething() {
        println("Doing something...")
    }
}

// Define the AppComponent
@Singleton
@Component
interface AppComponent {
    fun myDependency(): MyDependency
}

// Define the SubComponent that depends on AppComponent
@Singleton
@Component(dependencies = [AppComponent::class])
interface SubComponent {
    fun myDependency(): MyDependency
}

2. Create Hilt modules for each component:

@Module
@InstallIn(SingletonComponent::class)
object AppModule {
    @Singleton
    @Provides
    fun provideMyDependency(): MyDependency {
        return MyDependency()
        }
}

@Module
@InstallIn(SingletonComponent::class)
object SubModule {
    @Singleton
    @Provides
    fun provideMyDependency(subComponent: SubComponent): MyDependency {
        return subComponent.myDependency()
    }
}

3. Initialize the components:

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
    @Inject
    lateinit var myDependency: MyDependency // Injected dependency

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        myDependency.doSomething()
    }
}

In this example, the SubComponent depends on the AppComponent. By specifying dependencies = [AppComponent::class] in the @Component annotation of SubComponent, we declare the dependency.

When we request a MyDependency instance in the SubModule, Hilt will find it in the AppComponent and provide it to the SubComponent, allowing us to access the same instance across both components.

Component dependencies in Hilt allow us to structure our application's architecture effectively and share dependencies across different components without creating unnecessary singletons or polluting the global scope.

ย