Easy MVP library for android

By | April 17, 2018


Introduction

In part 3 of my series on architectural patterns in android, I wrote about MVP along with a sample android app and showed how using it can lead to more scalable, maintainable and extendable code.

There are two things about MVP I am not a fan of:

  • larger number of lines of boilerplate code compared to other architectural patterns: The following table compares the number of lines of code for a benchmark app written with no architecture, MVC and MVP

  • handling lifecycle-dependent operations like cancelling network connection when onStop  is called, or disposing the observables in RxJava  has to be done manually

The above motivated me to write a very handy MVP library (called ‘easy-mvp’) for implementing the MVP architectural pattern in android.

In this post, I am going to show in simple steps how you can write the exact same sample movie app of part 3  with absolutely no boilerplate code using ‘easy-mvp’ library. The library code is on GitHub for anyone wanting to dig into details.

 

Objective

Build a movie app in MVP architecture, which shows the user a list of movies containing a search keyword. Check here for more details and screenshots of the app. The full code is in the ‘mvp-easymvp’ branch of my Github repo.

 

Implementation Steps

Step 1

Add this to your app build.gradle :

 

Step 2

Create your View, e.g. MainView , by extending the BaseViewImpl< >  from the library. Inside the < > put the name of your Presenter, say MainPresenter :

Step 3

Create your Presenter, MainPresenter  in this example, by extending BasePresenterImpl<MainView,MainModel> , where MainModel  is the class name for your Model :

 

Step 4:

Create your Model, e.g. MainModel :

 

Step 5

Finally, create an Activity, namely MainActivity , and introduce the MainView  in it as:

where main_activity  is a layout holding a ViewGroup  for populating the View’s UI elements:

Conclusion

Using ‘easymvp’ for the sample movie app renders considerable reduction in the number of lines of code, from 238 to 217:

Cancelling network requests and RxJava observables when the app stops showing in the foreground is also very easy by adding them to the mCompositeDisposable  in the presenter. The library then automatically handles the lifecycle and cancels the network request and disposes the observable once the app goes to the background, so no memory leak will happen in that respect.

Leave a Reply

Your email address will not be published. Required fields are marked *