Skip to content

Instantly share code, notes, and snippets.

@wingsum93
Last active December 12, 2017 05:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wingsum93/310f020f7ee9feb10535e852bf930d31 to your computer and use it in GitHub Desktop.
Save wingsum93/310f020f7ee9feb10535e852bf930d31 to your computer and use it in GitHub Desktop.
kotlin pref convient
private class SharedPreferenceDelegate<T>(
private val context: Context,
private val defaultValue: T,
private val getter: SharedPreferences.(String, T) -> T,
private val setter: Editor.(String, T) -> Editor,
private val key: String
) : ReadWriteProperty<Any, T> {
private val safeContext: Context by lazyFast { context.safeContext() }
private val sharedPreferences: SharedPreferences by lazyFast {
PreferenceManager.getDefaultSharedPreferences(safeContext)
}
override fun getValue(thisRef: Any, property: KProperty<*>) =
sharedPreferences
.getter(key, defaultValue)
override fun setValue(thisRef: Any, property: KProperty<*>, value: T) =
sharedPreferences
.edit()
.setter(key, value)
.apply()
}
@Suppress("UNCHECKED_CAST")
fun <T> bindSharedPreference(context: Context, key: String, defaultValue: T): ReadWriteProperty<Any, T> =
when (defaultValue) {
is Boolean ->
SharedPreferenceDelegate(context, defaultValue, SharedPreferences::getBoolean, Editor::putBoolean, key)
is Int ->
SharedPreferenceDelegate(context, defaultValue, SharedPreferences::getInt, Editor::putInt, key)
is Long ->
SharedPreferenceDelegate(context, defaultValue, SharedPreferences::getLong, Editor::putLong, key)
is Float ->
SharedPreferenceDelegate(context, defaultValue, SharedPreferences::getFloat, Editor::putFloat, key)
is String ->
SharedPreferenceDelegate(context, defaultValue, SharedPreferences::getString, Editor::putString, key)
else -> throw IllegalArgumentException()
} as ReadWriteProperty<Any, T>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment