Broadcast streams
- Dart course
- Advanced
- Lesson 13/83
- 5 min
Learn multiple listeners with broadcast streams.
Broadcast streams
A standard Stream is single-subscription: a second listen throws. A broadcast stream allows multiple listeners.
To broadcast a stream, call .asBroadcastStream() or open it with StreamController.broadcast(). Every listener receives the same events.
Usage: fan out an event source (e.g. a timer, a WebSocket) to multiple parts of the app. However, stateful operators (buffer, debounce) may behave differently on broadcast streams.
asBroadcastStream
stream.asBroadcastStream() converts a single-subscription stream into a broadcast one. You can listen to the result as many times as you like.
Example: var b = Stream.fromIterable([1, 2, 3]).asBroadcastStream();. Both b.listen(print) and b.listen(print) receive 1, 2, 3.
Note: once asBroadcastStream is called, events are dispatched to listeners; a late listener misses earlier ones.
Practice Listen to a broadcast stream
Make main async. Add var s = Stream.fromIterable([1, 2, 3]).asBroadcastStream();. Add await s.forEach(print);.
Starter code
void main() {
// make async; turn fromIterable([1,2,3]) into broadcast; print via forEach
}Sample solution
void main() async {
var s = Stream.fromIterable([1, 2, 3]).asBroadcastStream();
await s.forEach(print);
}Expected output
1 2 3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is a property of broadcast streams?
- Allows multiple listeners Correct answer
- A second listener throws
- Accepts only a single listener
- Works only with Future
Explanation: a broadcast stream allows multiple listeners.
2 Convert to broadcast
var b = s.____();
var b = s.asBroadcastStream();
Explanation: asBroadcastStream turns a stream into a broadcast stream.
3 Match stream types
| Term | Meaning |
|---|---|
Single-subscription |
Single listener |
Broadcast |
Many listeners |
asBroadcastStream |
Conversion |
StreamController.broadcast |
Many-listener source |