【问题标题】:Android MVP with two fragments sharing the same data具有共享相同数据的两个片段的 Android MVP
【发布时间】:2017-09-12 20:35:09
【问题描述】:

我的应用有一个活动和两个片段。该活动仅用作片段容器。其中一个片段将数据显示为文本。第二个片段显示与图表相同的数据。此数据来自远程 JSON API。在 MVP 中,我们必须为每个视图(模块、模型、演示者、存储库...)复制相同的结构,我的应用程序从 JSON API 请求每个片段的数据,所以两次。我怎样才能拥有一个更有效的架构,让我尊重 MVP?

请参阅下面为我的两个片段实现的代码:

模块

@Module
public class PollutionLevelsModule {
    @Provides
        public PollutionLevelsFragmentMVP.Presenter providePollutionLevelsFragmentPresenter(PollutionLevelsFragmentMVP.Model pollutionLevelsModel) {
        return new PollutionLevelsPresenter(pollutionLevelsModel);
    }

    @Provides
    public PollutionLevelsFragmentMVP.Model providePollutionLevelsFragmentModel(Repository repository) {
        return new PollutionLevelsModel(repository);
    }

    @Singleton
    @Provides
    public Repository provideRepo(PollutionApiService pollutionApiService) {
        return new PollutionLevelsRepository(pollutionApiService);
    }
}

存储库

public class PollutionLevelsRepository implements Repository {
    private PollutionApiService pollutionApiService;

    public PollutionLevelsRepository(PollutionApiService pollutionApiService) {
        this.pollutionApiService = pollutionApiService;
    }

    @Override
    public Observable<Aqicn> getDataFromNetwork(String city, String authToken) {
        Observable<Aqicn> aqicn = pollutionApiService.getPollutionObservable(city, authToken);

        return aqicn;
    }
}

【问题讨论】:

标签: android json android-fragments mvp


【解决方案1】:

您必须在 Activity 中使用 MVP,以便只对 JSON API 进行一次请求。之后,从该 Activity 注册的所有片段都可以获取该请求。

【讨论】:

  • 谢谢。所以我在我的 MVP 结构化活动中从 API 获取数据,并使用 Bundle 将检索到的数据发送到我的两个片段,对吧?
  • 是的,您是对的。其他解决方案是您也可以从片段中调用活动的方法来获取响应。两种方式都可以正常工作。
  • 很高兴为您提供帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-17
  • 1970-01-01
  • 2016-03-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多