Is there a way to create a broadcast stream with the async* syntax [Dart]

Viewed 135

Taking this example from the Dart docs. Is there a way to make timedCounter() return a broadcast stream by definition?

Stream<int> timedCounter(Duration interval, [int? maxCount]) async* {
  int i = 0;
  while (true) {
    await Future.delayed(interval);
    yield i++;
    if (i == maxCount) break;
  }
}

Not looking for timedCounter().asBroadcastStream() nor with using a StreamController.
This question is more about if the syntax of defining a function with async* limits the result stream to be a single subscription.

1 Answers

No.

The Stream created by an async* function is always a single-subscription stream. If you want a broadcast stream, either use .asBroadcastStream() or, preferably, use a broadcast stream controller directly.

An async* function is intended to execute normally until it's done, driven by the normal control flow of a single (asynchronous) function.

Broadcast streams are usually used for firing events in response to other things happening. While you can do something like that using an async* function, it's actually very easy to make mistakes (like not catching an error and that terminating the stream before you intend to). So, at least for now, async* streams are single-subscription. (If I could change that, I'd make them multi-subscription like the Stream.multi constructor, where each listen gets its own sequence of events starting from scratch, not a broadcast stream where listeners share the same events).

Related