https://kotlinlang.org logo
Title
t

Tymmm1

12/13/2020, 9:25 PM
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

Tijl

12/13/2020, 9:45 PM
first()
1
t

Tymmm1

12/13/2020, 10:02 PM
@Tijl
first()
unfortunately has different behavior from
collect()
in that it throws an exception when the flow is empty.
t

travis

12/13/2020, 10:02 PM
firstOrNull
t

Tymmm1

12/13/2020, 10:03 PM
@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

Tijl

12/13/2020, 10:05 PM
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

Tymmm1

12/13/2020, 10:08 PM
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

Tijl

12/13/2020, 10:11 PM
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

Tymmm1

12/13/2020, 10:19 PM
Thanks.