https://kotlinlang.org logo
Title
t

Tgo1014

03/31/2023, 8:41 AM
Why the last line prints
false
if the line before it prints
1
?
val flow = MutableStateFlow(2)
val flowB: StateFlow<Boolean> = flow
    .map { it == 1 }
    .stateIn(GlobalScope, SharingStarted.Eagerly, false)

println(flow.value) // 2
flow.value = 1
println(flow.value) // 1
println(flowB.value) // false
f

franztesca

03/31/2023, 9:12 AM
The flow is asynchronous. When you emit 1 in
flow
, there is some time before
flowB
picks collects the value from
flow
, maps it and emits it. Your
println
statements are executed in that time, after 1 is emitted by
flow
but before 1 is collected by
flowB
. You can run
flowB
on an
Unconfined
dispatcher to make it process the value as soon as it is emitted by
flow
.
.stateIn(GlobalScope + Dispatchers.Unconfined