[英]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.