繁体   English   中英

是否可以缩短 DataStore Preferences 的代码

[英]Is it possible to shorten the code for the DataStore Preferences

问题- 使用DataStore PreferencesKotlin 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM