Dealing with view check’s in Presenters

I’d like to share the approach I use to check if the view attached to presenter is null or not, simplifying the code and make it more readable

Requirements

MVP pattern and lambdas (for now using Retrolambda)

Introduction

MVP is one of the best approach to separate you code in logical layer when you easily can make changes and maintain you code, of course it has some flaws but with some persistence you can find how to deal with them, on of those flays is checking the nullability of the view in presenter, of course in Kotlin you simply put a “?” in front of view and that’s it, but in java is not that simple, and writing every time ‘if statements” is not that pretty and consumes a lot of time and add frustration.

I want to write presenters with something like getView().doSomething() … it is possible in java to do that, you can look at this Github repository that I was using for some time, but almost all MVP libraries are using annotation processors, and have a lot of code, methods… so I was searching for a way to do it a little bit easier and by my self without using any library

Explanation

The best this I came to is something like getView(v -> v.doSomething()), not as pretty as expected but fairly easy to do and easy to write

The first step is to create you interfaces, the view and presenter, the presenter is not always necessary but I prefer to write it to.

Next, you write an abstract presenter that takes as template param the view.

Encapsulate the view in a weakReference, this way is easier to deal with memory leaks.

Inside the base presenter(the abstract class) you going to need a protected interface with a method that takes as param the template view.

And the last needed is a method that takes as param this interface, inside check if the view is not null and executes the method of the interface if so.

Example

The result is something like this:

public abstract class BasePresenter<V> {
    private WeakReference<V> view;

public void getView(ViewState<V> v) {
if (view.get() != null)
v.execute(view.get());
}

public void attachView(V view) {
this.view = new WeakReference<>(view);
}

protected interface ViewState<View> {
void execute(View v);
}
}

Dn example of the interfaces could be:

public interface ExampleContract {

interface View{
void doSomething();
}

interface Presenter{
void callSomething();
}

}

I write them inside another interface just to keep them organized.

An implementation of a presenter is something like this:

public class Presenter extends BasePresenter<ExampleContract.View>
implements ExampleContract.Presenter {

@Override
public void callSomething() {
getView(v -> v.doSomething());
}

}

Thats’it!

If you have any questions feel free to leave a comment or make a suggestion.