简体   繁体   中英

Is it possible to shorten the code for the DataStore Preferences

Problem - repeating piece of code when using DataStore Preferences and Kotlin Flow .
What Im talking about:

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"
         }
}

Is it possible to put the functionality inside the .catch { exception } in a separate function, with the ability to change Kotlin Flow?

You can create a suspend extension function on FlowCollector type and reuse it:

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"
        }
}

Or if you want to reuse the whole catch statement you can create an extension function on Flow :

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"
        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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