Best practice for using Shared Preferences in MVVM Android?

4.3k views Asked by At

I've been searching for the best approach to using Shared Preferences in MVVM architecture in Android but I could just find pieces and thus having no clear image over ho to do it in the best way. Therefore I have a few questions:

  1. Should I keep a singleton instance of a SharedPrefs over the app?
  2. Should ViewModel and Repository use Shared Preferences?
  3. Where to use them? Let's say there is a Fragment, a ViewModel and a Repository. Should I control the SharedPrefs from ViewModel for Fragment and Repository or should each one take care on their own? E.g. User clicks on a button to save a setting. Save in SP from fragment? Make a call to a method from ViewModel to save in SP? Or redirect further to Reposioty to use SP?

(*SP = Shared Preferences)

I would really appreciate to get some advice for the best practice of SharePreferences in MVVM Android

1

There are 1 answers

3
Alireza Mahfouzian On BEST ANSWER

enter image description here

this diagram represents the MVVM structure very well, in your case you want to save some data in your localDataSourece such as dataBase or Shared preference so it suggests that you do use your logic of saving in the repository level and call those functions from your ViewModel.

if you use the same reference of the shared preference it's best to use it as singleton and not create it every time you read or write it.