communicate between presenters in MVP android application

左心房为你撑大大i 提交于 2019-12-21 09:18:03

问题


I am using MVP pattern to build a small test android app. I have two fragments Fragment B (I am using for sliding drawer) and Fragment A (main fragment). Both fragments have their own presenters. when I click on sliding draw it should send message or invoke a method in Fragment A to update view. I want to ask , how both fragments presenter can talk under MVP. I know other solutions but I want to do it through MVP pattern.

Please suggest some options that MVP pattern follows to deal such scenarios.


回答1:


First of all, in MVP approaches, presenter and view have 1 to 1 relation to each other. If you want to communicate between presenters using bus system like EventBus/RxBus.

I recommend following tutorial. This is a 5 part series tutorial. In this tutorial, there are two fragments (Search and Cache Fragments) communicate between each other.

https://hackernoon.com/yet-another-mvp-article-part-1-lets-get-to-know-the-project-d3fd553b3e21




回答2:


In MVP, the View has the Context to start another View which is either another Fragment or Activity, so any transition between your Fragments has to be through the View. In your case, you have:

View1 (Sliding Drawer Fragment) <-----> Presenter1

View2 (Main Fragment) <-----> Presenter2

You click on a widget on View1 and want to navigate to some screen on View2 using MVP. You can do it like this:

---------------------- View 1 ---------------------

view1Item.setOnClickListener(new OnClickListener({
    presenter1.doWhenItem1IsClicked();
}))

---------------------- Presenter 1 ----------------

public void doWhenItem1IsClicked(){
    mView.showRelevantPageOnMainScreen()
}

---------------------- View 1 ---------------------

public void showRelevantPageOnMainScreen(){
    View2 view2=new View2(); //This is better to be done using DI
 getFragmentManager().beginTransaction().replace(R.id.your_main_page_layout,view2).commit();
}

---------------------- View 2 ---------------------

public void onCreate(){
super.onCreate();
presenter2=new Presenter2(this);
}
.
.
.

I have written an MVP library here you might find helpful.



来源:https://stackoverflow.com/questions/37231439/communicate-between-presenters-in-mvp-android-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!