Skip to content

Instantly share code, notes, and snippets.

@DHosseiny
Last active November 9, 2021 07:57
Show Gist options
  • Save DHosseiny/d4185e5ea8572531c8a16a14692e9578 to your computer and use it in GitHub Desktop.
Save DHosseiny/d4185e5ea8572531c8a16a14692e9578 to your computer and use it in GitHub Desktop.
DataStore Delegation
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
@DelicateCoroutinesApi
fun <T> DataStore<Preferences>.valueHolder(
key: Preferences.Key<T>,
defaultValue: T,
scope: CoroutineScope = GlobalScope
): DataStoreValueHolder<T> = DataStoreValueHolder(this, key, defaultValue, scope)
class DataStoreValueHolder<T>(
private val dataStore: DataStore<Preferences>,
private val key: Preferences.Key<T>,
private val defaultValue: T,
private val scope: CoroutineScope
) : ReadWriteProperty<Any?, T> {
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
return runBlocking(scope.coroutineContext) {
dataStore.data.map {
it[key] ?: defaultValue
}.first()
}
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
scope.launch {
dataStore.edit {
it[key] = value
}
}
}
}
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(
name = "settings"
)
class Usage(context: Context) {
var value by context.dataStore.valueHolder(KEY_BOOLEAN_PREFERENCES, false)
private companion object {
val KEY_BOOLEAN_PREFERENCES = booleanPreferencesKey("boolean_preferences")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment