https://kotlinlang.org logo
#coroutines
Title
# coroutines
l

Luis Munoz

08/26/2020, 3:27 AM
In a flow why doesn't catch capture errors for an onEach?
Copy code
suspend fun myErrorMethod(value: String) {
        throw RuntimeException("myErrorMethod $value")
    }

val scope = CoroutineScope(newFixedThreadPoolContext(2, "tPool") )

   val job = flow {
        repeat(3) {
            emit(it)
        }
        myErrorMethod("flow")
        emit(1)
    }.catch { e ->
        println("error ${e.message}")
        emit(11)
    }
    .onEach {
        println(it)
        myErrorMethod("flow")
    }
    .catch { e ->
        println("error ${e.message}")
        emit(12)
    }
    .onCompletion {
        println("on Complete")
        emit(10)
    }
    .launchIn(scope)
Copy code
0
error myErrorMethod flow
on Complete
t

taer

08/26/2020, 3:46 AM
I was curious, so I played w/ your code some(mostly differentiating the myError calls and the catches
here
Copy code
flow {
        repeat(3) {
            emit(it)
        }
        myErrorMethod("flow")
        emit(1)
That
myErrorMethod("flow"
never gets called. You emit 0 from the first loop. thus the first catch doesn't see it. the first onEach sees the 0, prints it, and then throws.the second catch is what is printing your message. It recovers the flow and emits 12. Then the oncpomplete emits the 10
1
l

Luis Munoz

08/26/2020, 4:18 AM
oh oops you are right, thank you
6 Views