Skip to content

Instantly share code, notes, and snippets.

@Jericho2Code
Last active January 17, 2020 12:11
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Jericho2Code/42068f1d4d9e8bbeab0c73fa1ffebb24 to your computer and use it in GitHub Desktop.
Save Jericho2Code/42068f1d4d9e8bbeab0c73fa1ffebb24 to your computer and use it in GitHub Desktop.
import android.content.SharedPreferences
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
class Preference<T>(
private val preferences: SharedPreferences,
private val name: String,
private val default: T
) : ReadWriteProperty<Any?, T> {
override fun getValue(thisRef: Any?, property: KProperty<*>): T = findPreference(name, default)
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
putPreference(name, value)
}
private fun <T> findPreference(name: String, default: T): T = with(preferences) {
val res: Any = when (default) {
is Long -> getLong(name, default)
is String -> getString(name, default)
is Int -> getInt(name, default)
is Boolean -> getBoolean(name, default)
is Float -> getFloat(name, default)
else -> throw IllegalArgumentException("This type cannot be saved into Preferences")
}
res as? T ?: default
}
private fun <T> putPreference(name: String, value: T) = with(preferences.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 cannot be saved into Preferences")
}.apply()
}
}
// SAMPLE
// before you need ref to SharedPreference
var myValue: String by Preference(
preference,
"KEY",
"DEFAULT_VALUE"
)
// put new value to shared pref
myValue = "NEW_VALUE"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment