简体   繁体   English

Android:MVP。 组件之间进行通讯的正确方法

[英]Android: MVP. Right way to communicaticate between components

I have implemented MVP pattern in my application. 我已经在我的应用程序中实现了MVP模式。 I have an additional layer which I call Repository , which is responsible for running HTTP asynchronous requests. 我有一个称为Repository的附加层,该层负责运行HTTP异步请求。 I have created OnTaskCompleteListener interface for communication between Repository and Model ( Model implements OnTaskCompleteListener ). 我已经创建了OnTaskCompleteListener接口,用于RepositoryModel之间的通信( Model实现了OnTaskCompleteListener )。 So when Repository finishes the request, it calls a method in Model and updates data. 因此,当存储库完成请求时,它将在Model中调用一个方法并更新数据。 Then, Model calls a method in Presenter with the same mechanism, to let it know that Model has been updated. 然后,模型以相同的机制调用Presenter中的方法,以使其知道模型已更新。 What I am worrying, is the chain of callbacks that comes from Repository up to Presenter . 我担心的是从RepositoryPresenter的回调链。 Is there a better way to communicate between components of MVP or is it the way to go? 是否有更好的方法在MVP组件之间进行通信? I did try "EventBus", but a large number of needed interfaces scared me off. 我确实尝试过“ EventBus”,但是大量必需的接口使我感到恐惧。 Observer did not seem fit as there is only one listener for each component (Model listens to Repository, Presenter listens to Model). Observer似乎不合适,因为每个组件只有一个侦听器(Model侦听Repository,Presenter侦听Model)。 Thank you. 谢谢。

After extensive reading, I came to a conclusion, that I do not need another class 'Repository' to delegate loading of data. 大量阅读后,我得出一个结论,即不需要另一个类“存储库”来委托数据加载。 The model actually should be responsible for loading and holding data . 该模型实际上应该负责加载和保存数据 Using a callback method parameter for the method of the presenter, that calls a method that loads data in the model is a great way to communicate between model and presenter. 使用演示者方法的回调方法参数,调用在模型中加载数据的方法是在模型与演示者之间进行通信的一种好方法。

Presenter.java Presenter.java

@Override
public void loadData(){
    mModel.loadData(new Callback{
        void onSuccess(){
            getView().notifyDataLoaded();
        }

        void onError(){
            getView().notifyErrorOccured();
        }
});

This way model, presenter and view are linked in this single method in very clear and intuitive manner. 通过这种方法,模型,演示者和视图以非常清晰和直观的方式链接在一起。 Hope this will help someone. 希望这会帮助某人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM