I am confused about Flow, but is there any way to have a Flow that functions in this fashion?
- Buffers data until delivered. No subscriber buffer until full, which won't ever happen
- When a subscriber comes in deliver everything in buffer and remove them from buffer as delivered.
- Subscriber can unsub and resub and it won't replay just deliver items that were emitted, but not yet delivered to a subscriber.
- Doesn't have to multicast should only be one subscriber. I tried MutableSharedFlow(extraBufferCapacity = 10), but from what I have just found if there is no subscriber when the event comes in it just disposes of it.
I am using x.onEach{}.collect() if that is the correct way.
CodePudding user response:
You can have this behaviour by using a single-consumer hot flow - a Flow
based on a Channel
.
Declare a Channel(BUFFERED)
as the variable/property you will use to send elements. Then you may expose it as a flow using channel.receiveAsFlow()
so a consumer can start/stop collecting as it sees fit. Elements will be buffered as long as no consumer collects elements.
If you want to avoid confusion for users of your API, you may want to expose a ReceiveChannel
directly. In some cases however, this makes things non-composable, so using receiveAsFlow()
allows you to declare a Flow
API despite the hotness, which is more composable.