dev90
dev90

Reputation: 7579

Should we create a separate repository for each Activity or single repository for entire app

I am following MVVM architecture for my app. In Activity I need to getNews() from a URL, if news is not already cached.

Activity will ask ViewModel to give the News Json and ViewModel will look into the repository, and decide to send data from local or remote repository.

Now the confusion stems from the following point: Should I create a separate Repository class for each Activity, or a general Repository class for the entire project with which each activity communicates. The repository class would be huge in the second approach.

I am unable to find out any official guideline on this topic, and I would like to know the best practice on this regard.

Upvotes: 16

Views: 3593

Answers (2)

Mohammed Junaid
Mohammed Junaid

Reputation: 1412

I am pretty late for this, but it might be helpful for anyone else coming here!

The best practice recommended by Google (as of 2023 December) when using Repository Pattern is to have a repository for each type of data source your app uses.

You can further read here: Add Repository and Manual DI

It further states that :

What is a repository?

In general a repository class:

  • Exposes data to the rest of the app.
  • Centralizes changes to data.
  • Resolves conflicts between multiple data sources.
  • Abstract sources of data from the rest of the app
  • Contains business logic

Upvotes: 3

Bmuig
Bmuig

Reputation: 1089

Creating a single repository for the whole app is definitely not a good idea, since that will become very large and completely unmanagable very fast.

I would suggest that you create separate repositories for every viewmodel and additionally services for data that is used by multiple viewmodels.

In your example that would mean that you have a NewsSource service that takes care of retrieving and caching the news JSON and have all your repositories that need that data retrieve it from there.

Upvotes: 20

Related Questions