Last active
April 1, 2022 17:36
-
-
Save chenzhang2006/4a6ce537fc4d369e2451b3aa45734148 to your computer and use it in GitHub Desktop.
Helper function for Flow with default value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
inline fun <T> Flow<T>.catchLog(default: T? = null): Flow<T> = this.catch { e -> | |
if (e is CancellationException) throw e | |
Timber.e( | |
e, | |
"Error from flow (${coroutineContext[CoroutineName]?.name}): " + | |
"${e.stackTraceToString()}" | |
) | |
default?.let { emit(it) } | |
} | |
// call-site | |
runBlocking { | |
flow { | |
emit(1) | |
throw RuntimeException("unexpected") | |
emit(2) | |
} | |
.catchLog(default = 0) | |
.collect { println(it) } | |
} | |
// result: | |
1 | |
Error from flow (name): [stacktrace] | |
0 // default in case of error |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment