Android MVP – Correct Way for Presenters to Communicate

androidArchitecturemvp

I have an activity with two fragments attached, Fragment/View A controlled by Presenter A and Fragment/View B controlled by Presenter B. View A is on the top half of the screen and does not change through the life of the activity. View B takes the lower half of the screen and is swapped out when navigating to another fragment/view.

The problem is that Presenter B needs to communicate up to View A or Presenter A to manipulate it by adding objects to it or changing how the data is represented. How can this be done without Presenter B knowing or caring that View A exists to keep these features separate? Also, not every Presenter B needs to manipulate View A.

            View A
         /
Activity  ----------------
         \
            View B

Some ideas I had and the problems they have

1) Presenter B -> View B -> Activity -> View A -> Presenter A -> View A

Problem: Duplicate common methods on each View B, duplicate method when calling to activity to then call to View A, boucing between View A and Presenter A to update the model

2) Presenter B -> Model A -> Presenter A -> View A

Problem: It makes sense for some data to pass through Model A and inform the presenter, but there are a few things that are not data related and just need to manipulate the view directly

3) Presenter B -> View A -> Presenter A -> View A

Problem: Two presenters are now controlling one view, boucing between View A and Presenter A to update the model

4) Use the bus to post events from Presenter B to Presenter A

Problem: The bus is too easy to abuse and interfaces are easier to follow the flow

5) Any other ideas?

Here is an example of our current code and the first idea described

https://gist.github.com/UndefinedPotato/c9011994d7e8958c50d6b92f7dcbfc37

Best Answer

By using events. Presenter B raises events when certain things occur. Anyone interested can listen. Right now it may be A, but in the future X,Y, & Z can listen too. B doesn’t care, it just keeps on raising the same events.

Some languages support events as first class citizens, but in Java this is often implemented as the observer pattern. In fact, the Android API even has Observer and Observable interfaces.

Related Topic