Hey, anyone aware of a way to `collect` just once ...
# coroutines
t
Hey, anyone aware of a way to
collect
just once from a
StateFlow
or
SharedFlow
? One can call
cancel()
on the job of the coroutine that is collecting but that seems a bit cumbersome...
t
first()
1
t
@Tijl
first()
unfortunately has different behavior from
collect()
in that it throws an exception when the flow is empty.
t
firstOrNull
t
@travis
firstOrNull
also has different behavior. It returns null if the flow is empty where
collect
would just block and wait until there is something.
t
StateFlow always has a value, StateFlow and SharedFlow also never complete
AFAIK a Flow is only seen as empty if it completes without emiting, since SharedFlow (and StateFlow) never complete, they can’t be empty then.
t
I think I saw an exception being thrown by
first()
when I was using it on a
SharedFlow
(with no initial value).
If I
collect()
on a
SharedFlow
no exception is thrown.
But let me double check.
t
incidentally, on StateFlow I’d just read
value
since reading that code it will be more clear it will not suspend (
first
behaves the same in this case but on other Flows like SharedFlow it can suspend)
👍 1
t
Thanks.