Best practice for using Shared Preferences in MVVM Android?
Asked Answered
M

1

9

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

Melody answered 8/5, 2022 at 10:20 Comment(0)
I
5

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.

Imaginary answered 8/5, 2022 at 10:33 Comment(3)
However, if I don't have a repository (not using a db) but only working with shared preferences, then I should update the shared preferences from ViewModel and not from Fragment. Right?Melody
shared preferences should be treated as it is a database because it is a local data source in your project so you have to use repositories to use its functions. you have to call the save function that is in viewModel from the fragment when the user wants to save data and your view model will call the repository function and the repository should call your singleton or whatever class you have for saving an object in your shared preference.Imaginary
Ok, but to get sharedPreferences, you need Context, which the Repository doesn't have. How do you get Context into your Repository (which is a singleton object, right?), OR how do you get sharedPreferences without Context?Stockroom

© 2022 - 2024 — McMap. All rights reserved.