https://kotlinlang.org logo
Title
l

Lilly

09/07/2021, 11:55 PM
Is there a flow operator that does "check condition, if true close flow otherwise keep flowing while the emitted value for this condition is not emitted downstream"? I would like to check if the first item is of specific type, if yes newer values are emitted downstream if no close the flow. I have played around with
withIndex
,
takeWhile
and
takeIf
but it doesn't let me close the flow. I'm not sure but does
takeWhile
close the flow if false is returned? Maybe a combination of multiple operators will do it. Any ideas?
s

streetsofboston

09/08/2021, 1:04 AM
I don't think you can 'close' just any Flow. A Flow emits data/values on its own schedule and manner. It has no idea of downstream operators or collectors. You can create your own operator that returns a new Flow that will close upon a certain condition, but you already discovered those: The
takeXxxx
operators for example.
✔️ 1
a

Andrea

09/08/2021, 1:12 AM
you could use the
onEach
{ `check`() } and the .
catch
{}, but the check is applied to all values, not only the first one, unless it fails and the flow stops emitting. It could work if your first value type is unique and cannot be present in any other position.
j

Joffrey

09/08/2021, 6:35 AM
takeWhile
does end the flow if the condition becomes false
☝️ 2