[英]Is it possible to shorten the code for the DataStore Preferences
問題- 使用DataStore Preferences和Kotlin Flow時重復一段代碼。
我在說什么:
override fun readSomeData(): Flow<String> {
return dataStore.data
.catch { exception ->
if (exception is IOException) {
emit(emptyPreferences())
} else {
throw exception
}
}
.map { preferences ->
preferences[PreferencesKey.someValue] ?: "null value"
}
}
是否可以將.catch { exception }中的功能放在單獨的 function 中,並能夠更改 Kotlin 流?
您可以在FlowCollector
類型上創建suspend
擴展 function 並重用它:
suspend fun FlowCollector<Preferences>.onCatch(exception: Throwable) {
if (exception is IOException) {
emit(emptyPreferences())
} else {
throw exception
}
}
fun readSomeData(): Flow<String> {
return flow<String>{}
.catch {
onCatch(it)
}.map { preferences ->
preferences[PreferencesKey.someValue] ?: "null value"
}
}
或者,如果您想重用整個catch
語句,您可以在Flow
上創建一個擴展 function :
fun Flow<Preferences>.onCatch() = catch { exception ->
if (exception is IOException) {
emit(emptyPreferences())
} else {
throw exception
}
}
fun readSomeData(): Flow<String> {
return flow<String> {}
.onCatch()
.map { preferences ->
preferences[PreferencesKey.someValue] ?: "null value"
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.