Python Streams: Asynchronous Data Flows & StreamControllers
While a `Future` delivers a single asynchronous value, a `Stream<T>` delivers a continuous sequence of asynchronous events over time (like user click events, WebSocket messages, GPS coordinates, or chat messages). Streams can be consumed using `.listen()` or `await for` loops, and produced programmatically via **`StreamController`**.
"A Future is a delivery package delivered once to your doorstep; a Stream is a flowing kitchen faucet that pours a continuous stream of water droplets over time until you turn off the handle."
Deep Dive: How It Works
Single-Subscription vs Broadcast Streams: Single-subscription streams allow only ONE listener; Broadcast streams (`Stream.broadcast()`) allow multiple concurrent subscribers.
`await for` Loop: Pauses and consumes stream events sequentially as they arrive.
`StreamController<T>`: A manager object with a `sink` (to add events/errors) and a `stream` (to listen to events).
Syntax Blueprint
// Creating a StreamController
final controller = StreamController<String>();
controller.stream.listen((msg) => print("Received: $msg"));
controller.sink.add("Event 1");
controller.close();Producing events via Sink and consuming via Stream subscription.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Adding multiple `.listen()` listeners to a single-subscription stream.Why it happens: Single-subscription streams throw `StateError: Stream has already been listened to`.
How to fix: Convert the stream using `.asBroadcastStream()` if multiple listeners are needed.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Listen to Periodic Stream
Create a stream `final stream = Stream.fromIterable(["A", "B", "C"]);`.
Use `await for (final item in stream) { print("Item: $item"); }`.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.