In all my projects I usually have two extension methods for SharedPreferences that don't require obtaining a SharedPreferences.Editor first.
This:
inline fun SharedPreferences.apply(modifier: SharedPreferences.Editor.() -> Unit) {
val editor = this.edit()
editor.modifier()
editor.apply()
}
Then I can use SharedPreferences like this:
sharedPrefs.apply {
putString("someStringKey", "someValue")
putInt("someIntValue", 911)
}
If you like it, I can open a PR to add this.
Another solution is to use delegation to keep a copy of the preference. That way, you will always be able to use apply() and you'll always avoid calling from IO if the variable is unchanged.
Here is my implementation
Anything delegated acts as if it's a normal variable
Most helpful comment
Another solution is to use delegation to keep a copy of the preference. That way, you will always be able to use
apply()and you'll always avoid calling from IO if the variable is unchanged.Here is my implementation
Anything delegated acts as if it's a normal variable