Dagger2 and qualifiers in dependent components

2019-08-09 23:50发布

问题:

I have an app component and a dependent component. The app component declares explicit dependencies, and the dependent component can inject those. However, when I have a dependency that I have to disambiguate with a @Qualifier, the dependent component is not able to inject that dependency.

This is the app component

@Component(modules = [AppModule::class, SchedulersModule::class, StorageModule::class])

@ApplicationScope
interface AppComponent {
    fun inject(app: Application)
    /* other stuff omitted for brevity */
    val bitmapCache: BitmapCache        
    @UiScheduler fun uiScheduler(): Scheduler
}

This is the scheduler module:

@Module
class SchedulersModule {
    @ApplicationScope
    @Provides
    @IoScheduler
    fun provideIoScheduler(): Scheduler = Schedulers.io()

    @ApplicationScope
    @Provides
    @UiScheduler
    fun provideMainThreadScheduler(): Scheduler = AndroidSchedulers.mainThread()
}

This is the qualifier:

@Qualifier
@Retention(AnnotationRetention.RUNTIME)
annotation class UiScheduler

And this is the dependent component:

@Component(
        dependencies = [AppComponent::class],
        modules = [EditEntryActivityModule::class, ViewModelModule::class]
)

@ActivityScope
interface EditEntryActivityComponent {
    fun inject(editEntryActivity: EditEntryActivity)
    fun inject(editEntryFragment: EditEntryFragment)
}

This is how the scheduler is injected in the fragment:

class EditEntryFragment : Fragment() {
    @Inject @UiScheduler lateinit var uiScheduler: Scheduler
    /* other stuff */
}

So why can the dependent component inject the bitmap cache, declared in the parent component, but not the UI scheduler? This is the error I get:

error: io.reactivex.Scheduler cannot be provided without an @Provides- or @Produces-annotated method.
  io.reactivex.Scheduler is injected at
      com.test.edit.EditEntryFragment.uiScheduler
  com.test.edit.EditEntryFragment is injected at
      com.test.edit.EditEntryActivityComponent.inject(arg0)
1 error

回答1:

Using @field:UiScheduler in class EditEntryFragment



回答2:

Try @Named annotition

@Inject @field:Named("UiScheduler") lateinit var uiScheduler: Scheduler

check out this issue