具有两个片段的Android MVP共享同一数据 [英] Android MVP with two fragments sharing the same data

查看:122
本文介绍了具有两个片段的Android MVP共享同一数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My app has one activity and two fragments. The activity is just used as a fragment container. One of the fragment show data as text. The second fragment shows the same data as a chart. This data come from a remote JSON API. As in MVP we have to replicate the same structure for each view (module, model, presenter, repository...) my app request the data from the JSON API for every fragment, so two times. How can i do to have a more efficient architecture allowing me to respect the MVP ?

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

See below the code implemented for my both fragments :

模块

@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;
    }
}

推荐答案

您必须在活动中使用MVP,以便仅一次请求JSON API.之后,从该活动注册的所有片段都可以获取该MVP.

You must use MVP inside your activity so that only one time request is done to JSON API.After that all fragments which register from that activity can able to get that.

这篇关于具有两个片段的Android MVP共享同一数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆