Skip to content

Instantly share code, notes, and snippets.

@agustarc
Created December 27, 2021 10:18
Show Gist options
  • Save agustarc/5f92376ca02108f321328c64a7b664b9 to your computer and use it in GitHub Desktop.
Save agustarc/5f92376ca02108f321328c64a7b664b9 to your computer and use it in GitHub Desktop.
suspend inline fun <T : Any> DataStore<Preferences>.readValue(key: Preferences.Key<T>, defaultValue: T): T {
return data.catch { recoverOrThrow(it) }.map { it[key] }.firstOrNull() ?: defaultValue
}
suspend inline fun <T : Any> DataStore<Preferences>.readValue(key: Preferences.Key<T>): T? {
return data.catch { recoverOrThrow(it) }.map { it[key] }.firstOrNull()
}
suspend fun FlowCollector<Preferences>.recoverOrThrow(throwable: Throwable) {
if (throwable is IOException) {
emit(emptyPreferences())
} else {
throw throwable
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment