In Mvp Is Onclick Responsibility Of View Or Presenter?
Solution 1:
OnClick should call a Presenter
method. You should do your business in presenter and if you need to update the ui you should define a method in your View
and call it from presenter.
You need a method for your View
ex:
publicvoidshowCounterCount(finalint totalClicks){
counterTextView.setText("Total clicks so far: "+totalClicks);
}
Also you need a method and a variable in your Presenter
:
int totalClicks = 0;
publicvoidonCounterButtonClicked(){
totalClicks++;
mView.showCounterCount(totalClicks);
}
And refactor your code like this:
counterButton.setOnClickListener(newView.OnClickListener() {
publicvoidonClick(View v) {
mPresenter.onCounterButtonClicked();
}
});
For more complex and clean architecture you can do your use case business in interactors. (In your example incrementing a counter value is a use-case for your application)
You can define an interactor and increment your counter value there.
CounterInteractor:
public CounterInteractor{
publicintincrementCounter(int currentCounter){
return currentCounter+1;
}
}
And refactor your presenter like below:
int totalClicks = 0;
CounterInteractor mCounterInteractor = new CounterInteractor();
publicvoidonCounterButtonClicked(){
totalClicks = mCounterInteractor.incrementCounter(totalClicks);
mView.showCounterCount(totalClicks);
}
With this approach you separate your business logic totally from presenters and re use your use-case concepts without duplicating code in presenters. This is more clean approach.
You can also check this git repo for different MVP Approaches. https://github.com/googlesamples/android-architecture/tree/todo-mvp-clean/
Good luck.
Edit:
Here's my lightweight wikipedia client project source: https://github.com/savepopulation/wikilight
I'm trying to implement MVP
. (MVP + Dagger2 + RxJava)
Solution 2:
In MVP, it is the responsibility of the View to know how to capture the click, not to decide what to do on it. As soon as the View captures the click, it must call the relevant method in the Presenter to act upon it:
------------------- View --------------------
button1.setOnClickListener(newOnClickListener({
presenter.doWhenButton1isClicked();
}));
------------------ Presenter ----------------
publicvoiddoWhenButton1isClicked(){
// do whatever business requires
}
I have a series of articles on architectural patterns in android, part 3 of which is about MVP. You might find it helpful.
Post a Comment for "In Mvp Is Onclick Responsibility Of View Or Presenter?"