Satnam Singh
Satnam Singh

Reputation: 33

Repository can be singleton in mvvm android?

I don't understand few things about repository in mvvm, also have seen multiple blogs and code templates. Every one of them doesn't match with other. So

  1. Why there is needs to have multiple Repositories classes? Why single repository shouldn't handle all the data IN OUT for the app?

  2. Why Repository shouldn't be a SINGLETON class in project?

  3. What a repository('s method) should provide to viewmodel Result(Sealed class) or actual response from a api like list(or error)?

  4. SharedPrefrences should be handled by Repository as well or not? if no why

    I believe Repository should be that part of your code which should process all the data from multiple source whether be database or network or sharedprefs. So what do you think?

Upvotes: 3

Views: 2636

Answers (1)

Daniyal Javaid
Daniyal Javaid

Reputation: 1636

  1. Purpose of repository is not only to manage requests/response but also provide a layer to keep responsibilities separated. If you have 2 modules (let's say Login and Registration), it is much better to keep repositories separated to keep things clean and simple rather than having a single repo with spaghetti code.

  2. This point is opinionated. IMO you can have singleton repositories because they are stateless i.e they do not hold any kind of data which may cause conflict between multiple ViewModels/Modules.

  3. Depends on you but it is much better to return Result. With Result you can handle Success Failure and Error Messages easily and return different Error Messages directly from repository rather than deciding in ViewModel what message to show. Messages can be either from server or internal exception messages.

  4. SharedPreferences is a datasource. Yes you can manage preferences using repository pattern.

Upvotes: 6

Related Questions