Multiple @Binds with same return class but different key

痴心易碎 提交于 2019-12-05 21:18:37

You'll need a separate binding on each Subcomponent:

@Module interface DemoActivitySubcomponentModule {
  @Binds abstract Activity bindContext(DemoActivity demoActivity);
  // ...other bindings unique to DemoActivity and not DemoActivity2
}

@Subcomponent(modules={DemoActivitySubcomponentModule.class})
public interface DemoActivitySubcomponent extends 
    AndroidInjector<DemoActivity> {
  @Subcomponent.Builder
  abstract class Builder extends AndroidInjector.Builder<DemoActivity> {}
}

Because of @BindsInstance Builder seedInstance(DemoActivity) in AndroidInjector.Builder, which Dagger calls in AndroidInjector.Builder.create() from DispatchingAndroidInjector, Dagger does know how to provide a DemoActivity instance at least. However, there's no built-in binding between DemoActivity and Activity (or Context), so the binding has to be made on the subcomponent instead of the component. By putting the module with that binding on the appropriate @Subcomponent, you can ensure that within each respective subcomponent the Activity binding goes to the correct type that Dagger knows about.

Note that the @Binds @IntoMap @ActivityKey(...) binding in DemoActivityModule still needs to go onto the ApplicationComponent, so the ApplicationComponent can determine which subcomponent to create from the class of the Activity being injected. You specifically want the new DemoActivitySubcomponentModule to go onto DemoActivitySubcomponent so that it makes the Activity-to-DemoActivity in a place where DemoActivity2Subcomponent can't see it.

As a side note, the problem you're seeing is the conflict between the two bindings to Activity, which happen in the same component. It's not quite right to say the same scope, because (though you might choose to add a scope annotation like @ActivityScope to each subcomponent) there is no scope annotation that would help you here. The seedInstance will apply only within each currently-unscoped subcomponent, which will combine with bindings in the ancestor components as well as the subcomponent-specific modules.

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