【发布时间】:2019-10-17 13:10:29
【问题描述】:
我有一些 MVP 模式的 Group 模块。我刚开始学习 Dagger2,我希望 GroupComponent 将存储库注入到 Presenter 中,并为 GroupFragment 提供 Presenter。
这是我的仓库:
public class GroupServerRepository {
@Inject
public GroupServerRepository(){}
我的演示者:
public class GroupPresenter implements LifecycleObserver {
private GroupServerRepository repository;
@Inject
public GroupPresenter(GroupServerRepository repository){
this.repository = repository;
}
组件:
@Component
interface GroupComponent{
GroupPresenter getPresenter();
GroupServerRepository getRepository();
}
片段:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_group, container, false);
GroupContracts.GroupComponent component =
DaggerGroupContracts_GroupComponent.create();
presenter = component.getPresenter();
所以我希望在生成的组件类中有下一个代码:
@Override
public GroupPresenter getPresenter() {
return new GroupPresenter(getRepository());
}
@Override
public GroupServerRepository getRepository() {
return new GroupServerRepository();
}
但不是这个,我有下一个:
@Override
public GroupPresenter getPresenter() {
return new GroupPresenter(new GroupServerRepository());
}
@Override
public GroupServerRepository getRepository() {
return new GroupServerRepository();
}
我试图重建项目,但没有帮助。
【问题讨论】:
-
我相信您需要在 GroupServerRepository 类中添加范围注释,例如
@Singleton。然后 dagger 每次都会重用同一个实例。