Can I cancel collecting a `StateFlow` from within ...
# coroutines
l
Can I cancel collecting a
StateFlow
from within the
collect
function? Let's say I received the value I expected and want to stop collecting.
k
Why wouldn't you do something more idiomatic like
Copy code
stateFlow.first { it == theValue }
l
Oh yes, that's much better!
I want to run an action when I get the value, so I assume
first
just suspends until the condition is true and I can call my action afterwards?
Copy code
coroutineScope.launch {
    stateFlow.first { it }
    action()
}
I'm just waiting for the
stateFlow
to become
true
Thanks for your quick help 🙏
k
I would say your sample is fine
c
You can also
Copy code
stateFlow
    .filter { it == theValue }
    .onEach { yourAction() }
    .first()
Your call on which is more readable
k
I personally dislike
onEach
because it’s inherently side effecty but either works
c
I want to run an action when I get the value
Well that's the definition of a side effect, isn't it?
l
Although just using
first
is more concise.
j
No it's the definition of an effect. A primary effect.
Side effects are like logging
e
btw the usual way to "stop" collecting is with
takeWhile
or
transformWhile
, but if you're only interested that it exists at all, then
first
followed by non-
Flow
code is simplest
151 Views