Hello all :wave: Is there a channel that emits it...
# coroutines
g
Hello all 👋 Is there a channel that emits its value to all subscribers, while suspending (keeping the value) if none is subscribed and then the value gets consumed?
p
That sounds a lot like what StateFlow does: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-state-flow/ It emits the latest value to new subscribers AFAIK
g
Yes i ve been using state flow for a different case. But state flow won’t consume the value after all subscribers received it. Well you can do it manually but was wondering if it could be done with another combination out of the box 📦
p
It's hard to do I think, as the flow/channel doesn't know if there are gonna be new subscribers subscribing after. Unless I'm not fully understanding the use case. Which is likely 😅
w
What do you mean consume the value? Should new subscribers not receive the value, assuming they subscribed after previous consumers received it?
g
Yes exactly that. I want to model one shot events, namely side effects, that can propagate to every subscriber, until someone handles it. Of course i can use state flow and then update the value when it’s handled but was wondering as i said if it’s something that can help me avoid manually updating after handling.
w
Not sure I follow. If you want the value to be handled by all subscribers, a regular Flow (not
StateFlow
) would do just that. Unless you want the value to only be handled by a single subscriber?
g
Not sure that there is a ready to use primitive for this Essentialy suspend until there are no subscribers and with subscribers work as standard BroadcastChannel/SharedFlow
g
What Andrey is saying. Yes probably it doesn’t exist. The closer i have found, is the broadcast channel but it doesn’t suspend and the other choice is a state flow that also won’t suspend but it will have its value saved. On that case i will have to manually “null” out the value after consuming. Probably i will go with the state flow. Thanks though 🙏 😊
g
Broadcast channel doesn’t suspend, it will be replaced with SharedFlow which also doesn’t suspend in such cases
Anyway, I would report your case to Kotlinx.coroutines tracker, some custom operator can be implemented on top of StateFlow, you can have an operator which creates StateFlow, increments some atomic counter on subscribe and decrement on unsubscribe, and buffer value if there is 0 subscribers and emit it on first subscriber
originally I thought that you need something like ReplaySubject for flows, but it also not what you need, if you don’t want to emit last N values to new subscribers