Search code examples
androidmvp

Android MVP persistence


I'm trying to implement the MVP pattern into my project following the android blueprints guide. Currently, I am holding the User (entity data) within my Presenter, which I really dislike, because, on every configuration change, the presenter fetches the user from the database.

My first question is:

  • Should I keep my data in the Repository (as I am using dagger 2 and the repository lives in the application scope) or should I keep it within the presenter and persist it there somehow. I would personally like to keep it in the presenter, however, I am trying to learn w/e the conventional way is.

I am also aware of android architecture components, ViewModel in particular, however, I would like to keep the MVP pattern instead of MVVM.

My second question is:

  • After achieving persistence, how should I go about using LiveData with MVP?

I've been stuck on this problem for quite a while and would love to finally get through it.

Cheers


Solution

  • Should I keep my data in the Repository or should I keep it within the presenter and persist it there somehow?

    You have an interesting question which once I had as well when I started working with MVP. Here is my 2 cents:

    There has been continuing discussions on the two options that you mentioned. I personally prefer the repository pattern. It is much cleaner IMO and the dealing with cases like screen rotation when a request is already in flight etc becomes easier with it. Also every time the device rotates, you need not fetch from the db. If you think that's expensive, maybe you can create a level of cache before db. There is a very interesting and detailed article: Presenters are not for persisting by Mike Nakhimovich, who during his time as Android Developer at New York Times worked on a library called Store which helps achieve the same. From the article:

    I'd propose using data stores which abstract away data loading. Rather than the presenter needing to cache the data, we can leverage the Repository pattern and create Data Providers/Stores that can get data from the network and cache it for when we need it. For one thing, this approach makes it easier to persist your data. Another advantage is that we have a single source of truth for our data. Finally, we can eliminate things like Interactors and just have your Presenter subscribe to your Stores whenever they need something for a view.

    Hope this helps a bit.