Dagger2 and qualifiers in dependent components

折月煮酒 提交于 2019-12-24 06:33:51

问题


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



来源:https://stackoverflow.com/questions/48046309/dagger2-and-qualifiers-in-dependent-components

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!