|
import android.content.SharedPreferences |
|
import kotlin.properties.ReadWriteProperty |
|
import kotlin.reflect.KFunction3 |
|
import kotlin.reflect.KProperty |
|
|
|
@Suppress("UNCHECKED_CAST") |
|
inline fun <reified T> sharedPreferences(sharedPreferences: SharedPreferences, key: String): SharedPreferencesNullableProperty<T> = |
|
when (T::class) { |
|
Boolean::class -> SharedPreferencesNullableProperty(sharedPreferences, key, false, |
|
SharedPreferences::getBoolean, SharedPreferences.Editor::putBoolean) |
|
|
|
Float::class -> SharedPreferencesNullableProperty(sharedPreferences, key, 0f, |
|
SharedPreferences::getFloat, SharedPreferences.Editor::putFloat) |
|
|
|
Int::class -> SharedPreferencesNullableProperty(sharedPreferences, key, 0, |
|
SharedPreferences::getInt, SharedPreferences.Editor::putInt) |
|
|
|
Long::class -> SharedPreferencesNullableProperty(sharedPreferences, key, 0L, |
|
SharedPreferences::getLong, SharedPreferences.Editor::putLong) |
|
|
|
String::class -> SharedPreferencesNullableProperty(sharedPreferences, key, null, |
|
SharedPreferences::getString, SharedPreferences.Editor::putString) |
|
|
|
Set::class -> SharedPreferencesNullableProperty(sharedPreferences, key, null, |
|
SharedPreferences::getStringSet, SharedPreferences.Editor::putStringSet) |
|
|
|
else -> throw IllegalStateException("Illegal property type: ${T::class}") |
|
} as SharedPreferencesNullableProperty<T> |
|
|
|
class SharedPreferencesNullableProperty<T>( |
|
private val sharedPreferences: SharedPreferences, |
|
val key: String, |
|
val defaultValue: T, |
|
val getValue: KFunction3<SharedPreferences, String, T, T>, |
|
val setValue: KFunction3<SharedPreferences.Editor, String, T, SharedPreferences.Editor>) |
|
: ReadWriteProperty<Any, T?> { |
|
|
|
override fun getValue(thisRef: Any, property: KProperty<*>): T? = |
|
if (!sharedPreferences.contains(key)) { |
|
null |
|
} else { |
|
getValue(sharedPreferences, key, defaultValue) |
|
} |
|
|
|
|
|
override fun setValue(thisRef: Any, property: KProperty<*>, value: T?) = |
|
sharedPreferences.edit().apply { |
|
if (value == null) { |
|
remove(key) |
|
} else { |
|
setValue(sharedPreferences.edit(), key, value).apply() |
|
} |
|
}.apply() |
|
} |