Home > Software design >  Kotlin Flow with a buffer and no replay
Kotlin Flow with a buffer and no replay

Time:08-19

I am confused about Flow, but is there any way to have a Flow that functions in this fashion?

  1. Buffers data until delivered. No subscriber buffer until full, which won't ever happen
  2. When a subscriber comes in deliver everything in buffer and remove them from buffer as delivered.
  3. Subscriber can unsub and resub and it won't replay just deliver items that were emitted, but not yet delivered to a subscriber.
  4. 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.

  • Related