Home > Back-end >  Is it possible to shorten the code for the DataStore Preferences
Is it possible to shorten the code for the DataStore Preferences

Time:04-30

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?

CodePudding user response:

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