janvladimirmostert
01/05/2022, 8:41 PMCasey Brooks
01/05/2022, 9:08 PMSharedFlow
and StateFlow
are both hot flows, or you can emit the events to a Channel and read the events from the channel with receiveAsFlow()
to process them with all the normal Flow operators.
The difference between the two approaches is mainly how many collectors do you want to allow. With Shared/State Flows, a single message will be sent to all collectors. If you want to ensure each message is only ever processed exactly once regardless of how many collectors are subscribed, then you'll want to use the Channel instead.janvladimirmostert
01/05/2022, 9:17 PMCasey Brooks
01/05/2022, 9:22 PMjanvladimirmostert
01/05/2022, 9:46 PMval state = MutableStateFlow(0)
launch {
state.collect {
println("State changed to $it")
}
}
Channels on the other hand with the receiveAsFlow as you mentioned, works great!
val channel = Channel<Int>()
launch {
channel.receiveAsFlow().collect {
println("Received $it on channel1")
}
}
launch {
channel.receiveAsFlow().collect() {
println("Received $it on channel2")
}
}
launch {
var i = 0
while (true) {
state.value = i
state.value = i
channel.send(i)
channel.send(i)
i++
delay(1000)
}
}
State changed to 110
Received 110 on channel1
Received 110 on channel2
State changed to 111
Received 111 on channel1
Received 111 on channel2
State changed to 112
Received 112 on channel1
Received 112 on channel2
Thanks for the help!gildor
01/06/2022, 9:17 AMsince it doesn’t react if the value stays the sameIt’s a case for SharedFlow
janvladimirmostert
01/06/2022, 11:32 AM