julian
07/02/2020, 1:46 AMmap
, if the number is over 5, you terminate the flow.octylFractal
07/02/2020, 1:47 AMcancel()
?octylFractal
07/02/2020, 1:47 AMjulian
07/02/2020, 1:49 AMjulian
07/02/2020, 1:50 AMoctylFractal
07/02/2020, 1:51 AMoctylFractal
07/02/2020, 1:51 AMcoroutineContext.cancel()
?Adam Powell
07/02/2020, 2:01 AMthrow CancellationException()
julian
07/02/2020, 2:01 AMval pf = flowOf(1,2,3).map { if (it == 3) coroutineContext.cancel() else it }
runBlocking {
val l = pf.toList()
println(l)
}
prints:
[1, 2, kotlin.Unit]
It's that last item kotlin.Unit
that's surprising.octylFractal
07/02/2020, 2:02 AMvoid
in kotlin, it always returns Unit
, so you're returning Unit
from cancel()
thereoctylFractal
07/02/2020, 2:02 AMCancellationException
would be betterjulian
07/02/2020, 2:03 AMjulian
07/02/2020, 2:06 AMCancellationException
works, but catch
must also be used to be able to get the items emitted before the exception is thrown. Otherwise partial collection doesn't occur.julian
07/02/2020, 2:06 AMZach Klippenstein (he/him) [MOD]
07/02/2020, 2:18 AMjulian
07/02/2020, 2:23 AMlouiscad
07/02/2020, 5:52 AMCancellationException
is not the right way as it's ambiguous with other cancellation causes. You can take a look at how the take
intermediate operator is done, and that can help to do what you want. Or you can copy transformWhile
that Zach linked, or wait for it to be merged (which might take a while).tseisel
07/03/2020, 7:37 PMtakeWhile
?