2017-04-17 188 views
3

我的应用程序有一个活动和两个片段。该活动仅用作片段容器。其中一个片段将数据显示为文本。第二个片段显示与图表相同的数据。这些数据来自远程JSON API。和MVP一样,我们必须为每个视图复制相同的结构(模块,模型,演示者,存储库...),我的应用程序会为每个片段请求来自JSON API的数据,这样两次。我怎么能有一个更高效的架构让我尊重MVP?Android 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; 
    } 
} 
+0

http://stackoverflow.com/questions/34257883/mvp-for-activity-with-multiple-fragments?rq=1 – Manish

回答

3

您必须使用MVP的活动内,仅一次的请求是为了JSON API。之后,从该活动注册的所有片段都可以获取该片段。

+0

谢谢。所以我从MVP结构化活动中的API中获取数据,并使用Bundle将检索到的数据发送给我的两个片段,对吧? – Laurent

+0

是的,你是对的。其他的解决方案是你可以从片段中调用活动的方法来获得响应。通过这两种方式,它会正常工作。 –

+0

非常感谢您的有用答案。 – Laurent

相关问题