Repository pattern with multiple remote data sources Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Repository pattern with multiple remote data sources without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I started learning Android development rather recently and made the mistake of creating god activities. I then learned about architecture and chose to refactor my existing code into an MVP architecture. So far so good but my next bottleneck is using the repository pattern. I understand that the repository is essentially an abstraction that the presenter calls to get data. It gracefully handles when to use a remote data source or a local data source, caching, etc.

But what if there needed to be multiple data sources? For example, I store and pull most data from Firebase Firestore but for complex querying and searching, I pull data (via REST through Retrofit) from an ElasticSearch instance. Both of these are remote data sources.

As such, instead of having my repository like so:

public class BookRepository implements BookDataSource {

    private final BookDataSource remoteSource;
    private final BookDataSource localSource;

    public BookRepository(@NonNull BookDataSource remoteSource,
                          @NonNull BookDataSource localSource){
        this.remoteSource = remoteSource;
        this.localSource = localSource;

It looks something like this:

public class BookRepository implements BookDataSource {

    private final FirebaseFirestore firestore;
    private final Retrofit retrofit;
    private final SomeLocalSource local;

    public BookRepository(@NonNull FirebaseFirestore firestore,
                          @NonNull Retrofit retrofit,
                          @NonNull SomeLocalSource local){
        this.firestore = firestore;
        this.retrofit  = retrofit;
        this.local     = local;

As you can see, what I am passing changes the structure and if I were to, in the future, move to a different database, I’d have to refactor everywhere the repository is used. How can I improve/fix this?

I’ve provided a little diagram of the flow:

data flow


I’m sure there’s probably a better solution but I simply introduced another layer of abstraction

enter image description here

We are here to answer your question about Repository pattern with multiple remote data sources - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji