我真的迷路了,希望你能帮助我。我使用MVP和dagger2编程应用程序。其中一项活动(让我们说 A )在FragmentStatePagerAdapter中包含片段( B )。活动和片段都有自己的演示者。我处理片段中的输入( B ),并从中传输数据" up"主要演示者( B - > A )(活动保留片段)和那里( A )我处理网络连接。
为此,我需要片段演示者( B )中的主要演示者( A )的实例。我曾试图在片段图上使用依赖,但是不是获取已经存在的演示者实例,而是在每个init创建新的实例。有什么建议我怎么能得到类似单身但使用ActivityScope?
图表:
@ActivityScope
@Component(modules = GiftListModule.class, dependencies = AppGraph.class)
public interface GiftListGraph extends AppGraph{
void inject(GiftListActivity giftListActivity);
GiftListPresenter getGiftListPresenter();
final class Initializer {
public static GiftListGraph init(AppGraph appGraph, GiftListView giftListView) {
return DaggerGiftListGraph.builder()
.giftListModule(new GiftListModule(giftListView))
.appGraph(appGraph)
.build();
}
}
}
模块:
@Module
public class GiftListModule {
private final GiftListView giftListView;
public GiftListModule(GiftListView giftListView) {
this.giftListView = giftListView;
}
@Provides GiftListView provideGiftListView() {
return giftListView;
}
@Provides GiftListPresenter provideGiftListPresenter(GiftListView giftListView) {
return new GiftListPresenterImpl(giftListView);
}
}
B图:
@FragmentScope
@Component(modules = GiftDetailsModule.class, dependencies = GiftListGraph.class)
public interface GiftDetailsGraph {
void inject(GiftDetailsFragment giftDetailsFragment);
GiftDetailsPresenter getGiftDetailsPresenter();
final class Initializer {
public static GiftDetailsGraph init(GiftListGraph giftListGraph, GiftDetailsView giftDetailsView) {
return DaggerGiftDetailsGraph.builder()
.giftDetailsModule(new GiftDetailsModule(giftDetailsView))
.giftListGraph(giftListGraph)
.build();
}
}
}
B模块:
@Module
public class GiftDetailsModule {
private final GiftDetailsView giftDetailsView;
public GiftDetailsModule(GiftDetailsView giftDetailsView) {
this.giftDetailsView = giftDetailsView;
}
@Provides GiftDetailsView provideGiftDetailsView() {
return giftDetailsView;
}
@Provides GiftDetailsPresenter provideGiftDetailsPresenter(GiftDetailsView giftDetailsView,
GiftListPresenter giftListPresenter) {
return new GiftDetailsPresenterImpl(giftDetailsView, giftListPresenter);
}
}
主要应用
public class MainApp extends Application {
private static MainApp sInstance;
protected AppGraph appGraph;
protected GiftListGraph giftListGraph;
@Override
public void onCreate() {
super.onCreate();
sInstance = this;
appGraph = AppGraph.Initializer.init(this);
}
public static MainApp getInstance() {
return sInstance;
}
...
public GiftListGraph getGiftListGraph(GiftListView view) {
return giftListGraph = GiftListGraph.Initializer.init(appGraph, view);
}
public GiftDetailsGraph getGiftDetailsGraph(GiftDetailsView view) {
return GiftDetailsGraph.Initializer.init(giftListGraph, view);
}
... }
感谢您的帮助,你可以给我:)
答案 0 :(得分:2)
从DI的角度来看,您看到了正确的行为。当您调用获取列表图或详细图时,您正在构建全新的图。 (请参阅初始化程序调用中的新模块调用)。因此,您每次都会获得新实例。
我会考虑的选择很少。
一: 在活动范围定义回调接口。有活动实现它。在创建片段图的过程中,将回调impl实例(activity或some impl class)作为参数传递。您的片段a / b演示者可以将其用作依赖项。现在两个片段演示者都会收到回电。
二: 使用在应用程序范围或活动范围内运行的事件总线或广播接收器。用它来回发布消息。
希望这会给你一些想法。