Skip to content

Instantly share code, notes, and snippets.

@chenzhang2006
Last active April 1, 2022 17:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chenzhang2006/4a6ce537fc4d369e2451b3aa45734148 to your computer and use it in GitHub Desktop.
Save chenzhang2006/4a6ce537fc4d369e2451b3aa45734148 to your computer and use it in GitHub Desktop.
Helper function for Flow with default value
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