MVP in Android or Presenter First Design Pattern
Model-View-Presenter(MVP) Model is started using in android lately and it is gaining popularity.
MVP model makes your code more understandable.
What is MVP design pattern?
In MVP the presenter assumes the functionality of the “middle-man”. In MVP, all presentation logic is pushed to the presenter
So, we divide our product code in three parts model view and presenter. Roughly saying we put our UI code in view and our model or any network calls in model. As stated above presenter acts as a “middle-man” and model and view do not interact with each other directly. This comes with certain pros and cons :-
- Code become easy to understand.
- Easy to manage.
- Good for big projects as it is understandable by any new person to the project.
- Testing becomes easy as we can test our model and view independently.
- Lot of classes comes into place as every Screen will have its presenter model and view classes.
- Need to write extra code for implementing simple feature.
- Difficult for someone to understand it initially.
What is Presenter First Design Pattern?
In Presenter First Design Pattern we follow the MVP with always checking the presenter first. When we have to check any feature we just open the presenter file and see the flow.
As seen in the Diagram Presenter contains all the logic of the application and access the model and view as necessary.
Understand the flow of Presenter First
As shown in the diagram above, First we call the presenter if any event occurs.
For example as in the diagram above if any button click occurs on our screen in Android then presenter will will call the ViewImpl class which implements view interface.
view.onButtonClick().subscribe(value -> model.getValue(value))
Presenter asks view to setDisplay() or addListener() then view ask the presenter for the value to be displayed, then in response to that, presenter asks the value from the model class, model gets the value from the database or from network service or from stub model and returns the value to the presenter. Presenter sends it to view and asks it to show then finally view shows the value on the screen.
view.onButtonClick().subscribe(value -> model.getValue(value)).subscribe(gotValue -> view.showValue(gotValue)));
I tried to implement Presenter First Design Pattern in the code here.