Async Algorithms `multicast(_:)` or equivalent

Hi All,

I understand that there is currently a focus on honing what's already in place, but I would be really appreciative of a multicast(_:) equivalent now that the AsyncChannel/AsyncThrowingChannel sequences are in place.

As justification: I think we have some great algorithms for transforming, combining and merging sequences, but think that the functionality of a multicast(_:) or equivalent algorithm will help to create some tidy APIs at the sequence pipeline source.

What I'd like to achieve is the ability to:

  1. Lazily initialise a source sequence upon connection of the first consumer
  2. Share that sequence with subsequent consumers
  3. Clean-up of the sequence after the last consumer cancels.

This is great for things like accelerometer data, or tapping audio data. Where you may have multiple interested consumers at any one time, and you only want to start sampling when a consumer is present, and also cease sampling when interested consumers have gone.

In Combine/Rx it might have been achieved by creating a custom Publisher that handled the initialisation/clean-up piece (achieved with an AsyncStream, today) then placing it behind a multicast(_:) operator to share with multiple consumers and referenceCounted() (not in Combine) to handle discarding it when all the consumers are done.

This makes for really elegant API where consumers can all share a single sequence and not need to concern themselves with how to start or stop whatever the underlying source might be.

2 Likes