How do Streams work in Dart and what is the difference between single and broadcast streams?
TL;DR: Streams represent asynchronous sequences of values. Single-subscription streams can have one listener (file reads, HTTP responses). Broadcast streams support multiple listeners (user events, BLoC state). StreamController creates streams imperatively.
Full Answer
A Stream<T> is like an asynchronous Iterable<T>. Instead of pulling values synchronously, you subscribe and values are pushed to you as they arrive.
Single vs Broadcast
| Aspect | Single Subscription | Broadcast |
|---|---|---|
| Listeners | One only | Multiple simultaneous |
| Buffering | Buffers until listener attached | No buffering โ misses events |
| Use cases | File read, HTTP response | UI events, BLoC streams |
| Create | StreamController<T>() | StreamController<T>.broadcast() |
BLoC uses broadcast StreamControllers internally so multiple widgets can listen to the same state stream simultaneously without 'already has a listener' errors.
Code Examples
Listener 1: Hello Listener 2: Hello Listener 1: World Listener 2: World 4 16
Common Mistakes
- โForgetting to close() StreamControllers โ causes memory leaks (stream stays open forever)
- โListening to a single-subscription stream twice โ throws 'Stream has already been listened to'
Interview Tip
BLoC pattern is built on broadcast streams. Understanding single vs broadcast explains why BLoC uses StreamController.broadcast() and why you can have multiple BlocBuilders listening to the same bloc.