Skip to content

Instantly share code, notes, and snippets.

@egorshustov
Created February 28, 2020 16:32
Show Gist options
  • Save egorshustov/eba695b4a66c45cba194ca33af2f55f8 to your computer and use it in GitHub Desktop.
Save egorshustov/eba695b4a66c45cba194ca33af2f55f8 to your computer and use it in GitHub Desktop.
import android.content.SharedPreferences
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
class DelegatedPreference<T>(
private val sharedPrefs: SharedPreferences,
private val key: String,
private val defValue: T
) : ReadWriteProperty<Any?, T> {
override fun getValue(thisRef: Any?, property: KProperty<*>): T = findPreference(key, defValue)
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
putPreference(value)
}
@Suppress("UNCHECKED_CAST")
private fun findPreference(key: String, defaultValue: T): T = with(sharedPrefs) {
val foundValue: Any = when (defaultValue) {
is String -> getString(key, defaultValue)
is Int -> getInt(key, defaultValue)
is Long -> getLong(key, defaultValue)
is Float -> getFloat(key, defaultValue)
is Boolean -> getBoolean(key, defaultValue)
else -> throw IllegalArgumentException("This type cannot be obtained from Preferences")
}
foundValue as T
}
private fun putPreference(value: T?) = with(sharedPrefs.edit()) {
value ?: return@with
when (value) {
is String -> putString(key, value)
is Int -> putInt(key, value)
is Long -> putLong(key, value)
is Float -> putFloat(key, value)
is Boolean -> putBoolean(key, value)
else -> throw IllegalArgumentException("This type cannot be saved into Preferences")
}.apply()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment