Let the view handle the lifecycle in MVP by using RxJava

Ferhat Parmak
2 min readAug 13, 2016

--

Suppose that your view has a method called showProducts. Simply, it updates the items of recyclerview. If your view is a Fragment, you have to call this method after onViewCreated to be make sure the view is inflated.

If we let the presenter know when onViewCreated is called, it can call showProducts on right time. But handling the view’s lifecycle is not the presenter’s job. View should handle that. But how?

At first example our view is calling presenter’s onViewCreated method to notify presenter that the view is ready. Here is our view and presenter classes:

This is a bad example for two reasons. First, there is a chance you may never get to show the product list if the service returns product list before onViewCreated. Second, presenter needs to store and check if the view is ready.

The problem is showing the product list happens asynchronously at view because of waiting the onViewCreated call. That means view’s showProducts can return an observable that waits onViewCreated call and the presenter can subscribe it at whenever it wants.

To do this first we need to bind onViewCreated event to an observable and let showProducts method return an observable by using that lifecycle observable.

Now showProducts just returns an observable and updates the list after view is created. And it does not need to call presenter’s onViewCreated method.

By the way, this is not a complete example. Lifecycle subject should be updated at onViewDestroyed call and the presenter should unsubscribe the previous showProducts observable if getProducts observable can produce multiple items. This can be achived by using switchMap operator instead of flatMap.

--

--