PART 6. ADVANCED ANDROID TUTORIAL - Implementing MVP

Unfortunately, there is no “standard” way to implement MVP for Android apps 😐. There are many variations of MVP and developers adjust this pattern idea to their own style and needs. And since this is my blog, it's my way or highway 👹. My style of MVP implementation is more focused on testability rather than ease of implementation. It is based on two principles:
  1. The View should be dumb: Reduce the functionality of the View to the absolute minimum. The View should only be responsible for rendering the screen and should have no data contained in it. This improves the testability dramatically.
  2.  The Presenter should be framework-independent: Presenter should not depend on Android classes. This part can be tricky sometimes. But do not worry, there are plenty of examples online and with practice, you would get better at it. 
For looking at my way of implementing MVP,  go to the addnotes section of the screens module in the sample application. Here the Fragment AddNoteFragment is our View. This View implements a simple interface which are the methods related to rendering something on the screen. This ensures that our View is dumb or passive. 

Make your Presenter implement an interface which should contain the methods it needs to act as a  communicator between the Model and the View. As you can see, this Presenter is handling the responsibility of adding a new note to the the database (our Model) and informing the Fragment (our View) about the state of the application. There is no direct communication between the Model and the View.  

The only part remaining now is to provide the "Presenter" to our View. The best way to do that is by dependency injection. In the AddNoteFragment you can see an example of that.  In our sample application there is a separate module for injecting the presenters wherever required.




@Module
public class PresenterModule {

    private final Context mContext;

    public PresenterModule(Context mContext) {
        this.mContext = mContext;
    }

    @Provides
    @Singleton
    public WeatherPresenter provideWeatherPresenter() {
        return new WeatherPresenterImpl(mContext);
    }

    @Provides
    @Singleton
    public WeatherDetailPresenter provideWeatherDetailPresenter() {
        return new WeatherDetailPresenterImpl(mContext);
    }

    @Provides
    @Singleton
    public NotesListPresenter provideNotesListPresenter() {
        return new NotesListPresenterImpl(mContext);
    }

    @Provides
    @Singleton
    public AddNotePresenter provideAddNotePresenter() {
        return new AddNotePresenterImpl(mContext);
    }

    @Provides
    @Singleton
    public NoteDetailPresenter provideNoteDetailPresenter() {
        return new NoteDetailPresenterImpl(mContext);
    }

}

In the next lesson of the series, we will discuss how to implment a RecyclerView without breaking the MVP principle.

No comments:

Powered by Blogger.