Sobes.tech
Middle+

What is a Subcomponent in Dagger?

sobes.tech AI

Answer from AI

A Subcomponent in Dagger is a component that extends the functionality of a parent component by providing dependencies defined in its modules, as well as dependencies provided by the parent component.

Key features:

  • Inherits dependencies: The Subcomponent has access to all dependencies provided by the parent component.
  • Extends the dependency graph: It adds its own modules and, consequently, its own dependencies.
  • Limited scope: Its lifecycle is usually shorter than that of the parent component and is tied to a specific context or type.
  • Used for modularity: It allows dividing the dependency graph into smaller, manageable parts.

Creating a Subcomponent:

  1. Declare the Subcomponent:
    interface FeatureComponent {
        // Methods to provide dependencies
    
        @Subcomponent.Factory
        interface Factory {
            fun create(): FeatureComponent
        }
    }
    
  2. Bind the Subcomponent to the parent component:
    @Component(...)
    interface AppComponent {
        fun featureComponent(): FeatureComponent.Factory
    }
    

Using the Subcomponent:

val appComponent = DaggerAppComponent.create()
val featureComponent = appComponent.featureComponent().create()
What is a Subcomponent in Dagger? — Android - sobes.tech