Skip to content

Instantly share code, notes, and snippets.

@gregisdumb
Created February 19, 2021 20:43
Show Gist options
  • Save gregisdumb/95709d4531fbe01983c38ace08f5a865 to your computer and use it in GitHub Desktop.
Save gregisdumb/95709d4531fbe01983c38ace08f5a865 to your computer and use it in GitHub Desktop.
Kotlin Flow with catch still completes
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
/**
* When a flow throws an exception, I would expect the catch operator to allow the flow to continue.
* But instead, it halts the flow.
*
* Furthermore, I see that if I place the catch operator AFTER onEach, it never executes. It only
* executes if I place it BEFORE onEach, why is that?
*/
fun main() {
// Flow of lambdas that return a String (or throw an Exception)
flowOf<() -> String>({ "Hello " }, { error("error") }, { "World" })
// Map to the result of the invocation of the lambda
.map { it() }
// This line will emit the error String, but then the flow completes anyway.
// I would expect the flow to continue onto "World"
.catch { emit("[1. Exception caught] ") }
// Prints the emitted String
.onEach { println(it) }
// If you comment out the above catch, I would expect this catch to emit instead, but it never gets here.
.catch { emit("[2. Exception caught] ") }
.launchIn(GlobalScope)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment