๐ŸŽ“ A1Learner
๐Ÿ”
0 of 24 lessons completed

Dart Broadcast Streams

A broadcast stream is a stream that allows more than one listener. Every listener receives the same values while it is subscribed.

A value before any listener is lost

The controller is a synchronous broadcast controller. The value 1 is added before either listener subscribes, so nobody prints it, and each later value reaches both listeners in subscription order.

import 'dart:async';

void main() {
  var controller = StreamController<int>.broadcast(sync: true);
  controller.add(1);
  controller.stream.listen((value) {
    print('first heard $value');
  });
  controller.stream.listen((value) {
    print('second heard $value');
  });
  controller.add(2);
  controller.add(3);
  controller.close();
}

Two full readings of one stream

asBroadcastStream turns the stream into a broadcast stream. Both toList calls start before either one is awaited, so each listener collects every value.

import 'dart:async';

Future<void> main() async {
  var stream = Stream.fromIterable([10, 20, 30]).asBroadcastStream();
  var first = stream.toList();
  var second = stream.toList();
  print(await first);
  print(await second);
}

One listener leaves, the other stays

Both listeners hear the value 1. The first subscription is then cancelled, so only the second listener hears the value 2.

import 'dart:async';

Future<void> main() async {
  var controller = StreamController<int>.broadcast(sync: true);
  var first = controller.stream.listen((value) {
    print('first heard $value');
  });
  controller.stream.listen((value) {
    print('second heard $value');
  });
  controller.add(1);
  await first.cancel();
  controller.add(2);
  controller.close();
}

Example

import 'dart:async';

void main() {
  var hub = StreamController<String>.broadcast(sync: true);
  hub.stream.listen((event) {
    print('screen shows $event');
  });
  hub.stream.listen((event) {
    print('log records $event');
  });
  hub.add('start');
  hub.add('stop');
  hub.close();
}

Key points

  • A single-subscription stream allows only one listener over its whole life.
  • A broadcast stream allows many listeners at the same time.
  • Every active listener receives each value added while it is subscribed.
  • A broadcast stream does not buffer values for listeners that arrive later.
  • A value added before any listener exists is lost.
  • Cancelling one subscription ends only that listener, and the other listeners keep receiving values.

In this example, one broadcast hub feeds two listeners at once. The screen listener prints each event first because it subscribed first. The log listener prints the same event straight after it, for both start and stop.

Note

Broadcast suits values that several parts of a program need at once, such as shared events.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท DartPad

Exercise

What happens to a value added to a broadcast stream before any listener subscribes?