T
T
Tsuzukeru2021-03-20 12:39:09
Android
Tsuzukeru, 2021-03-20 12:39:09

Do I need to declare subcomponents inside the dagger component?

I noticed that the code uses subcomponent declarations in the subcomponents module.
I saw other examples where this is not done (components and subcomponents are not related in any way). What does this module give to the application?

@Singleton
@Component(
    modules = [
        AppModule::class,
        AppModuleBinds::class,
        ViewModelBuilderModule::class,
        SubcomponentsModule::class
    ]
)
interface AppComponent {

    @Component.Factory
    interface Factory {
        fun create(@BindsInstance applicationContext: Context): AppComponent
    }

    fun addEditTaskComponent(): AddEditTaskComponent.Factory
    fun statisticsComponent(): StatisticsComponent.Factory
    fun taskDetailComponent(): TaskDetailComponent.Factory
    fun tasksComponent(): TasksComponent.Factory

    val tasksRepository: TasksRepository
}

@Module(
    subcomponents = [
        TasksComponent::class,
        AddEditTaskComponent::class,
        StatisticsComponent::class,
        TaskDetailComponent::class
    ]
)
object SubcomponentsModule

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2021-03-20
@Tsuzukeru

In this way, you can tell the dagger that this subcomponent will be a subcomponent specifically for a specific (or several) components. This can be useful if you do not want to get it (or its factory / builder) by hand from the component, but inject it.
For example:

@SubComponent
interface MySubComponent{
...
}

@Module(subcomponents=[MySubComponent::class])
interface SubcomponentsModule

@Component(modules=[SubcomponentsModule::class])
interface MyComponent{
  fun inject(what: MyClass)
}

class MyClass{
  @Inject 
  lateinit var subcomponent:. MySubComponent

  fun inject (){
    // Инжектим с помощью MyComponent
  }

In this case, it is not necessary to write a function in the component interface that returns a subcomponent.
And if you want to write such a function, and pull it with your hands directly from the component, then you can not enumerate it in the module.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question