Peter
01/10/2024, 1:05 PMMutableSharedFlow
, but I would like to have event collected only once, for every new subscriber (collection).Peter
01/10/2024, 1:07 PMval flow = MutableSharedFlow<String>()
launch {
flow.emit("x")
}
delay(500)
// I want this to receive "x"
launch {
flow.collect {
println("rx1: $it")
}
}
delay(500)
// I don't want this to receive event again
launch {
flow.collect {
println("rx2: $it")
}
}
Peter
01/10/2024, 1:08 PMMutableSharedFlow<String>(replay = 1)
, both collect calls will receive "x", which I don't wantGleb Minaev
01/10/2024, 1:23 PMChannel
for this purpose:
val channel = Channel<String>()
launch {
channel.send("x")
}
delay(500)
// This one will receive the element
launch {
channel.receiveAsFlow().collect {
println("rx1: $it")
}
}
delay(500)
// This one won't receive any element
launch {
channel.receiveAsFlow().collect {
println("rx2: $it")
}
}
Peter
01/10/2024, 1:29 PMPeter
01/10/2024, 1:41 PMPeter
01/10/2024, 1:41 PMsend()
or buffer capacityRatul Sarna
01/11/2024, 7:00 AMChannel
, the second collector will never receive the events. Channels can only deliver to one subscriber. If you want your second collector to receive future events (not the one that was previously emitted), then a SharedFlow
with extraBufferCapacity=1
would work.Gleb Minaev
01/11/2024, 7:05 AMval channel = Channel<String>()
launch {
channel.send("x1")
channel.send("x2")
channel.send("x3")
channel.send("x4")
channel.send("x5")
}
delay(500)
// This one will receive the element
launch {
channel.receiveAsFlow().collect {
println("rx1: $it")
delay(1000)
}
}
delay(500)
// This one won't receive any element
launch {
channel.receiveAsFlow().collect {
println("rx2: $it")
delay(1000)
}
}
prints
rx1: x1
rx2: x2
rx1: x3
rx2: x4
rx1: x5
that shows both collectors had their time to collect the elements.Ratul Sarna
01/11/2024, 7:20 AMbuszi0809
01/11/2024, 4:43 PMprivate val mutableEvents = Channel<Event>(Channel.Buffered)
val events: Flow<Event> = mutableEvents.receiveAsFlow()