Skip to content

Instantly share code, notes, and snippets.

@niihelium
Created February 11, 2020 17:44
Show Gist options
  • Save niihelium/015c9c2dac70d770825e362f28b97dfc to your computer and use it in GitHub Desktop.
Save niihelium/015c9c2dac70d770825e362f28b97dfc to your computer and use it in GitHub Desktop.
fun <B, T : B, R : B> Flow<T>.exceptionTransform(errorHandler: suspend (exception: Exception) -> R): Flow<B> {
return flow {
var fromDownstream = false
try {
collect { value ->
try {
emit(value)
} catch (e: Exception) {
fromDownstream = true
throw e
}
}
} catch (e: Exception) {
if (fromDownstream) throw e
emit(errorHandler(e))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment