簡體   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