I tried to combine several SharedFlow
into one StateFlow
using stateIn
. But my StateFlow
seems not updating after I emit new value to it's SharedFlow
source. I found out that the problem is from how I used stateIn
.
Here is the simplified code I am using (you can run it from kotlin playground).
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
fun main() = runBlocking {
val sourceFlow = MutableSharedFlow<Int>()
val stateFlow = sourceFlow.stateIn(GlobalScope, SharingStarted.Lazily, 0)
val job = launch { stateFlow.collect() }
sourceFlow.emit(99)
println(stateFlow.value)
job.cancel()
}
println(stateFlow.value)
prints out 0
when it should prints 99
. I already follow through this documentation about stateIn but still can not find the issue. Someone knows where I did wrong?