Search code examples
androidrepository-patternretrofit2mvpandroid-sharedpreferences

Android: Repository pattern in MVP and SharedPreferences


I'm building an app using MVP and I'm using a repository pattern. I have a local data source, which is a DB where I store certain information. I have a remote data source, in which using Retrofit, I make an API request. This request has a @Query, and that is a String that is stored in the SharedPreferences. I thought of adding the SharedPreferences to the Repository, as a data source, but since the remote data source should make use of these SharedPreferences -which would be a different data source than the remote- I don't see this architecture so clear anymore.

Thanks a lot for the help in advance.


Solution

  • I think many people over complicate the idea of repositories. The Repository pattern is really just a specific type of the Facade pattern. It is just an abstraction layer which sits between the true data sources (Models) and the consumers.

    Let's say we have a system that deals with weather data. In this case I see nothing wrong with having three Modal classes:

    • WeatherHttp
    • WeatherDb
    • WeatherPrefs

    These can all be members of your repository class injected through the constructor. All three of these are hidden from the consumers (UI) behind a single repository class:

    • WeatherRepository

    which might have a single public method:

    public void getWeatherForecasts(Callback<List<Forecast> forecastCallback);
    

    or Rx:

    public Observable<List<Forecast>> getWeatherForecasts();
    

    Behind the scenes of that method you might well make an http call to fetch the latest data, a database call to save the majority of the details and a shared prefs edit to save the timestamp of the last time the data was fetched. The idea is you are free to change the implementation at any time and the consumers don't care.

    The single most important thing about implementing a repository is you must not leak the implementation details. No network classes, database DAOs or SharedPreference keys should be exposed by the public API of the repository.