Swift Async Algorithms Proposal: Broadcast (Previously Shared)

I’ll jump in here to say I haven’t been actively developing my own ideas on this further, but I still firmly believe that the ideal solution to this looks quite a bit different to those above.

The crux of it is that the range of problems that this algorithm should attempt to solve is broader than a single algorithm.

Firstly, as you begin designing a multicast algorithm such as the one above, it becomes clear that there are many variations on a 'broadcast' algorithm, and therefore it's important that we design a solution to accommodate future enhancements.

The following comment by @ktoso summarises some of these:

Secondly, and perhaps more contentiously, I'm still unclear as to why this family of broadcast algorithms is expected to be chained (like map or filter) rather than being source algorithms (like AsyncStream or Subject's in the Rx/Combine world.)

The argument that I've heard to date is that programmers will find the 'chaining' algorithms simpler to understand as they struggle with the concept of Subjects in Rx/Combine.

However, I think that this is to miss some of the benefits of this model.

One of the big things that I think new programmers struggle with is that they are unable to iterate over source sequences (such as AsyncStream) multiple times – they're 'single shot'. Concerningly, the behaviour when you do is undefined.

If we were to instead adopt the source algorithm approach to multicasting, we would benefit from not only a range of multicasting options, but also a range of source algorithms that can safely be iterated multiple times. (And also designed to accommodate other issues such as back pressure.)

Of course, this approach would take some design effort, likely the introduction of a new AsyncSource type (roughly equivalent to a Subject) in the stdlib and then a new chained operator to multicast via said AsyncSource types. But I think it would go a long way to solving many of the shortcomings we have with AsyncSequence today.

7 Likes