RecyclerView in MVP — Passive view’s approach

Andrzej Chmielewski
AndroidPub
Published in
3 min readJul 21, 2017

--

One of the most important questions which arise in my head when working with RecyclerViews (or any other adapter views for that matter) in passive view approach is how to handle accessing data.

Most of the times people tend to create a Collection (let it be a List) field within the adapter, holding all the data that it needs to display. This sucks, because in MVP (model-view-presenter) we typically get this data in presenter and most likely store it there (or in Presentation Model, on which you can read more here), this makes the list to be referenced (or worse: copied) in two different places, which doubles our effort to keep those two in sync when making changes.

First of all, storing the data within the adapter itself and manipulating it (by removing, adding, or updating elements) breaks the passive view’s principle and general MVP pattern, as all the presentation’s logic should be a part of presenter. So how to tackle that problem?

Lets make our adapter “notify” presenter about it’s needs and treat each item in the collection as separate MVP view that was “requested” by the user:

First thing you might notice is that we pass the holder to our presenter.

“How come?! Presenter should not depend on Android framework! You are now tightly coupling presenter with Holder class! You bastard!”

No worries! Take a look at the RepositoryViewHolder's implementation:

As you can see, our RepositoryViewHolder is implementing RepositoryRowView which is a typical MVP View’s interface:

The presenter expects the interface instead of the concrete implementation:

This way, the whole logic of providing number of elements as well as data for each row is moved to our presenter without breaking the dependency rule of clean architecture (presenter knows nothing about concrete implementations of the view layer, nor knows anything about the android framework).

Adapter’s responsibility is to orchestrate events of rendering certain row views and calls the presenter to set up them properly. If you happen to have a list of elements that can be manipulated, each such manipulation should be notified to presenter which will take proper actions.

If you liked this post, make sure to 💚 it below and follow me on Medium

--

--