Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android MVP, how to coordinate multiple views?

Tags:

android

mvp

I have a presenter P. It is meant to control everything for some type of view V. I have multiple views like this: V1, V2, ... Vn. Interacting with one view Vx, can have effects on other another views Vy.

What is the best way to coordinate this? Should the presenters talk to each other? Should the presenter have references to all views?

like image 455
Deal Avatar asked May 22 '26 14:05

Deal


2 Answers

One View should know nothing about other ones. The View should communicate with its Presenter only. One Presenter also shouldn't know about other Presenters. To avoid presenters cohesion use events (EventBus, Otto, RxJava Subjects...).

like image 81
Torbik Avatar answered May 25 '26 09:05

Torbik


One approach is presenter P holding view V and view V inherit V1, V2,...Vn. Methods will be accessible for V across all View containers (Fragments and Activities).

public interface MainView extends BaseView, ErrorView{ //V
  void showProducts(@Nullable List<Product> products);
} 


public interface BaseView{ //V1 
   void setLoading(boolean loading);
   void showConfirmationDialog(@StringRes int title, @StringRes int message);
}

public interface ErrorView{ //V2
  void showErrorSnackBar(@StringRes int message);
}


public class ProductListFragment extends ... implements MainView{


}

In my experience, this works fine, beside the clutter and empty methods, which is not good in terms of readability.

Holding references of other Presenters inside your main presenter is fine as long as you ensure they are alive. This could lead to anti-pattern.

Another approach is holding each presenter separately and each of them consume the events standalone:

@Override
public void showProducts(List<Product> products){
   // do something with products that Presenter1 has dispatched for presenting
   presenter2.doSomethingOnProducts();
}

This is seamless communication between the interested parties in the result.

Mixing Observer pattern with MVP is fine too.

like image 42
Nikola Despotoski Avatar answered May 25 '26 09:05

Nikola Despotoski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!