8

I am curious about the role of the repository in the MVVM architecture .If you decide to add repository to your project, will this repository be responsible only for data from database or network ? The question is about SharedPreferences or Files , should I hold the repository responsible for that , or should I keep them in the ViewModel .

coroutineDispatcher
  • 7,718
  • 6
  • 30
  • 58
  • Think this way: in your App, you need something to show on the View. That "thing" will be provided by Repository. Don't think too much about "how Repository do that", it will come later. Just now you need to make sure you have that thing from Repository, and you use it correctly. Now next, implement the Repository to correctly return that thing for you. Now you have some choices: database, network or both? Or just SharedPref for a single true/false flag? – Nguyễn Hoài Nam Apr 26 '19 at 01:21
  • I see , whic also means , thank you . – coroutineDispatcher Apr 26 '19 at 03:12
  • If you want , you can post your answer below so I can verify it. – coroutineDispatcher Apr 26 '19 at 07:07

1 Answers1

6

From what I understand in MVVM I can say:

  • Repository should be responsible for all data that your project component ask for. Whether it's from Database or API.

  • Let repository grab all data from Database/API/Server/etc. Then you grab data from that repository.

  • You can have multiple repository if you need, like API Repository/FirebaseRepository/RoomRepository etc...

  • You can merge multiple data sources into one repository, but you need to handle that manually.

MohammadL
  • 2,398
  • 1
  • 19
  • 36
  • 1
    Yes , I have correctly used the sharedpreferences instance on the repository . So I would count this as correct . Check this use case [here](https://gist.github.com/stavro96/a54ac9f89aa8ad8b55f44baf55e170c1) – coroutineDispatcher May 05 '19 at 16:24
  • https://gist.github.com/coroutinedispatcher/a54ac9f89aa8ad8b55f44baf55e170c1 – coroutineDispatcher Mar 03 '20 at 18:36
  • 1
    I create a separate class for shared preferences. Then use this as the Repository as a single source of data. Check for more detail: https://arkapp.medium.com/how-to-use-shared-preferences-the-easy-and-fastest-way-98ce2013bf51 – abdul rehman Dec 05 '20 at 10:22