Created
August 20, 2021 17:14
-
-
Save KlassenKonstantin/7cb6c74d2713bb843d6ddb78e8e505cc to your computer and use it in GitHub Desktop.
Blocking access to DataStore<Preferences> with Enum support
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private class Blocking<T>( | |
private val dataStore: DataStore<Preferences>, | |
private val prefKey: Preferences.Key<T> | |
) : ReadWriteProperty<Any, T?> { | |
override fun getValue(thisRef: Any, property: KProperty<*>): T? = runBlocking { | |
dataStore.data.map { | |
it[prefKey] | |
}.firstOrNull() | |
} | |
override fun setValue(thisRef: Any, property: KProperty<*>, value: T?): Unit = runBlocking { | |
dataStore.edit { | |
it[prefKey] = value!! | |
} | |
} | |
} | |
private class BlockingEnum<T : Enum<T>>( | |
private val dataStore: DataStore<Preferences>, | |
private val prefKey: Preferences.Key<Int>, | |
private val default: T, | |
private val clazz: Class<T> | |
) : ReadWriteProperty<Any, T> { | |
override fun getValue(thisRef: Any, property: KProperty<*>): T = runBlocking { | |
dataStore.data.map { | |
it[prefKey]?.let { | |
clazz.enumConstants!![it] | |
} | |
}.firstOrNull() ?: default | |
} | |
override fun setValue(thisRef: Any, property: KProperty<*>, value: T): Unit = runBlocking { | |
dataStore.edit { | |
it[prefKey] = value.ordinal | |
} | |
} | |
} | |
/** | |
* Usage: | |
* var foo by datastore.blocking(KEY_NAME) | |
* var bar by datastore.blockingEnum(INT_KEY_NAME, SomeEnum.DEFAULT) | |
**/ | |
fun <reified T> DataStore<Preferences>.blocking(key: Preferences.Key<T>) = Blocking(this, key) | |
fun <reified T : Enum<T>> DataStore<Preferences>.blockingEnum(prefKey: Preferences.Key<Int>, default: T) = BlockingEnum(this, prefKey, default, T::class.java) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment