Skip to content

Instantly share code, notes, and snippets.

@cesclong
Created January 6, 2022 07:42
Show Gist options
  • Save cesclong/236b2cc8824ed9b1991b003d7258549b to your computer and use it in GitHub Desktop.
Save cesclong/236b2cc8824ed9b1991b003d7258549b to your computer and use it in GitHub Desktop.
使用委托类实现简化SharedPreference的使用
class PreDelegate<T>(
private val name: String,
private val default: T,
private val isCommit: Boolean = false,
private val prefs: SharedPreferences
) {
operator fun getValue(thisRef: Any?, property: KProperty<*>): T {
return getPref(name, default) ?: default
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
value?.let {
putPref(name, value)
}
}
private fun <T> getPref(name: String, defalut: T?) = with(prefs) {
val result: Any? = when (defalut) {
is Long -> getLong(name, defalut)
is String -> getString(name, defalut)
is Int -> getInt(name, defalut)
is Boolean -> getBoolean(name, defalut)
is Float -> getFloat(name, defalut)
else -> throw IllegalArgumentException("This type is not supported")
}
result as? T
}
private fun <T> putPref(name: String, value: T) = with(prefs.edit()) {
when (value) {
is Long -> putLong(name, value)
is String -> putString(name, value)
is Int -> putInt(name, value)
is Boolean -> putBoolean(name, value)
is Float -> putFloat(name, value)
else -> throw IllegalArgumentException("This type is not supported")
}
if (isCommit) {
commit()
} else {
apply()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment