LeFFaQ
LeFFaQ

Reputation: 3

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?

Upvotes: 0

Views: 192

Answers (1)

Sergio
Sergio

Reputation: 30715

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

Upvotes: 1

Related Questions