stateIn
with SharingStarted.Eagerly
doesn't really immediately start collecting
#4006
Labels
stateIn
with SharingStarted.Eagerly
doesn't really immediately start collecting
#4006
An example was submitted to us (slightly simplified):
The reason is that the subscription of
stateIn
only happens when the thread becomes available, which is only atdelay
in this example. DespiteEagerly
promising that the subscription will happen immediately, theemit
call is lost.Adding a
yield
afterstateIn
fixes the issue, asstateIn
gets a chance to finish its initialization.This behavior is actually intentional (
kotlinx.coroutines/kotlinx-coroutines-core/common/src/flow/operators/Share.kt
Lines 206 to 208 in 1a0287c
The code that ensures delivery of the initial element is tricky to write, as it requires knowingly starving the dispatcher of its threads that could perform the initialization code of
stateIn
in parallel. Also, the use cases are unclear, and it doesn't seem like this guarantee is even specified anywhere.We should either document that
Eagerly
can sometimes fail to even run the initialization code ofcollect
(for example, to subscribe to a shared flow) or change this behavior.The text was updated successfully, but these errors were encountered: