在MVP模型和dagger2中访问片段演示者的存储库

时间:2018-12-18 07:35:41

标签: android repository-pattern dagger-2 android-mvp

我在带有匕首的mvp中使用存储库模式。在应用范围中,我绑定了RemoteDataSource和LocalDataSource:

@Binds
    @AppScope
    @Remote
    abstract MainDataSource RemoteDataSource(RemoteDataSource remoteDataSource);

    @Binds
    @AppScope
    @Local
    abstract MainDataSource LocalDataSource(LocalDataSource localDataSource);

然后我将主存储库注入了应用程序范围:

 @Inject
    public MainRepository(@Remote MainDataSource remoteDataSource,
                          @Local MainDataSource localDataSource) {
        this.remoteDataSource = checkNotNull(remoteDataSource);
        this.localDataSource = checkNotNull(localDataSource);
    }

现在在mainpresenter的片段范围中,我在其承包商中通过了 MainRepository

@MainFragScope
@Component(modules = {MainFragModule.class}, dependencies = AppComponent.class)
public interface MainFragComponent {

演示者构造器:

private MainDataSource remoteDataSource;
private MainDataSource localDataSource;
 @Inject
    public MainPresenter(MainRepository repository, ArrayAdapter<String> typesAdapter) {
        this.repository = checkNotNull(repository);
        this.typesAdapter = checkNotNull(typesAdapter);
    }
@Override
public void loadChart(String district, String date, String type) {
    remoteDataSource.loadChart(district,date,type);
}

RemoteDataSource中,我有一个名为loadChart的方法,其工作是通过改造从远程服务器获取数据:

   public void loadChart(String district, String date, String type) {
        JsonObject joParam = new JsonObject();
        apiService.getAnalyticalReport(joParam).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    if (response.isSuccessful()) {
                    // need presenter reference to pass response to it

获取数据后,我需要将此数据从服务器返回到片段演示者(MainPresenter)。我需要演示者引用。如何在不破坏 mvp 角色的情况下获得主持人!?因为在 AppScope 中,我无法访问 MainPresenter

1 个答案:

答案 0 :(得分:0)

以恕我直言的方式,在解决MainPresenterremoteDataSource之间的通信之前,最好先解决MainDataSourceMainRepository之间的通信。因为有这样的桥梁

演示者-> MainRepository-> MainDataSource

MainDataSourceMainRepository可以为其用户提供交流的界面。同样,通过这种方式,MainDataSourceMainRepository不需要MainPresenter

所以数据传输将像这样

  • MainRepository(实现接口A)-> MainDataSource(提供 界面A)

  • MainPresenter(实现接口B)-> MainRepository(提供 界面B)