【发布时间】:2018-06-29 11:20:25
【问题描述】:
社区您好,我无法理解 dagger 2 以新方式添加子组件(在 dagger 2.7 中添加)。请参见下面的示例:
@Component(modules = {AppModule.class, MainActivityBinder.class})
@Singleton
interface AppComponent
{
inject(MyApplication _)
}
@Subcomponent(modules = ActivityModule.class)
interface ActivitySubcomponent
{
inject(MainActivity _)
@Subcomponent.Builder
interface Builder
{
@BindInstance
Builder activity(Activity activity)
ActivitySubcomponent build();
}
}
初始步骤:我有AppComponent 是我的根组件,它为AppModule 提供单例(改造、okhttp 等)。在ActivitySubcomponent 中,我提供ActivityModule 具有指定给该活动的依赖项。现在必须将子组件添加到AppComponent,因此我以新的方式创建了名为MainActivityBinder 的指定模块,该模块具有@Module.subcomponents 注释,指向绑定子组件,但我有第一个问题,它的主体应该是什么绑定模块?
@Module(subcomponents = ActivitySubcomponent.class)
public class MainActivityBinder
{
//what body of this class should be ??
}
我知道,这个想法是我可以绑定子组件或其构建器。第二个问题何时绑定构建器,何时绑定子组件?例如我的ActivitySubcomponent 需要活动上下文,所以我创建了为ActivityModule 提供上下文的构建器,在这种情况下,在MainActivityBinder 中提供一个构建器会更好吗?第三个问题如何调用组件构建器以及如何获取应用组件的子组件?在标准子组件工厂中,我添加了返回子组件的AppComponent 方法,我可以定义参数(例如给出活动上下文,如下所列)
@Component(modules = {AppModule.class})
@Singleton
interface AppComponent
{
ActivitySubcomponents newActivitySubcomponents(Activity activity);
inject(MyApplication _);
}
// in MainActivity
appComponent.newActivitySubcomponents(this).build().inject(this);
所以在新的子组件添加方法中实现了这种行为?
【问题讨论】:
-
为什么不使用 dagger-android ?一切都更加简单。
-
@Zuluft 你的建议离题了,我的目标是理解 Module.subcomponents,我读到的文档说:“使用Module.subcomponents更好,因为它允许Dagger检测是否曾经请求过子组件。通过父组件上的方法安装子组件是对该组件的显式请求,即使从未调用过该方法。”,所以我想尝试测试新的工作方式,但我不能正确定义的绑定模块。
标签: android dagger-2 subcomponent