Lukas Lechner
09/22/2022, 9:28 AMRuntimeException
in the collect
block caught by the try-catch
in the flow
builder?Sam
09/22/2022, 9:31 AMcollect
is actually run as part of the call to emit
. Use the catch
operator instead if you don’t want that behaviour (I think…)denis090712
09/22/2022, 9:36 AMfun interface Collector: (Int) -> Unit
fun main() {
val flow: (Collector) -> Unit = { emit: Collector ->
emit(1)
}
val collect = Collector { next: Int ->
error("oops")
}
flow(collect)
}
Lukas Lechner
09/22/2022, 9:50 AMSam
09/22/2022, 9:51 AMLukas Lechner
09/22/2022, 9:52 AMSam
09/22/2022, 9:56 AMEither
type from #arrow which has a few advantages over Result
.Sam
09/22/2022, 9:56 AMCasey Brooks
09/22/2022, 2:21 PM.collect { }
basically wraps flow { }
in such a way that emitted values flow down the chain, and exceptions flow back through all those layers in the opposite direction. It’s the same principle for why a function returns a value but exceptions are bubbled up the caller instead, because that’s the underlying mechanism and thought process of Flows: just a nested sequence of suspending function callsEric Chee
09/22/2022, 6:18 PMflow( emit( collect() ) )
and when collect throws an exception, it bubbles up to emit cuz emit was the caller/trigger of the collect call
Just as any other exception bubbles up to its caller. Did i understand that correctly?Casey Brooks
09/22/2022, 6:28 PMflow { }
and collect { }
to see that this is literally how the code flow is set up: emit()
directly calls the lambda passed to collect { }
. Things can get much more complicated with other operators, but this is the general principle behind it all