Anko: SharedPreferences extensions ?

Created on 26 Dec 2017  路  1Comment  路  Source: Kotlin/anko

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.

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

>All comments

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

AndwareSsj picture AndwareSsj  路  4Comments

HarryTylenol picture HarryTylenol  路  3Comments

nkanellopoulos picture nkanellopoulos  路  4Comments

vlonjatg picture vlonjatg  路  3Comments

SuleymanovTat picture SuleymanovTat  路  4Comments