Sub topic 15
Streams and async generators
This chapter assumes you can write async and await code with Future, handle errors with try/on/catch, and use List and iterable methods such as map and where. It covers how Dart models a sequence of asynchronous values, how to produce one with async*, and how to consume one safely.
From one future to many values
A Future<T> delivers one result later. A Stream<T> delivers zero or more results over time, then optionally finishes. Typical sources are user taps, file reads, socket data, and timers. Flutter widgets such as StreamBuilder consume streams, so this model matters beyond the language itself.
A stream can emit three kinds of events:
- Data events carry a value of type
T. - Error events carry an error and an optional stack trace.
- A done event signals that no more events will arrive.
| Row | Future | Stream |
|---|---|---|
| Values delivered | Exactly one (or one error) | Zero or more, plus errors |
| Consumed with | `await`, `.then` | `await for`, `.listen` |
| Producer syntax | `async` | `async*` with `yield` |
| Can be consumed twice | Yes | Not by default |
Producing values with async*
A function marked async* returns a Stream<T>. Inside it, yield emits a value and return ends the stream. This is the example from the plan:
Stream<int> countTo(int n) async* {
for (var i = 1; i <= n; i++) {
yield i;
}
}
Future<void> main() async {
await for (final value in countTo(3)) {
print(value);
}
}await for waits for each event, runs the loop body, then waits for the next. The loop ends when the stream sends its done event. It must appear inside an async function.
Generators are lazy
The body of an async* function does not run when you call it. It starts when someone listens, and it can pause while the listener is paused or busy.
Stream<int> noisy() async* {
print('generator started');
yield 1;
yield 2;
}
Future<void> main() async {
final s = noisy();
print('stream created');
print('first: ${await s.first}');
}The output is stream created, then generator started, then first: 1. Calling noisy() only builds the stream object. The first getter listens, takes one event, and cancels the subscription.
Delegating with yield*
yield* forwards every event of another stream, including errors, before the generator continues.
Stream<int> countdown(int n) async* {
for (var i = n; i > 0; i--) {
yield i;
}
}
Stream<String> launch() async* {
yield* countdown(3).map((n) => '$n...');
yield 'liftoff';
}
Future<void> main() async {
await for (final line in launch()) {
print(line);
}
}This prints 3..., 2..., 1..., and liftoff. Use yield* instead of an inner await for plus yield when you only need to pass events through.
Consuming a stream
There are two main ways to consume a stream.
await foris sequential and reads like a normal loop. Errors thrown by the stream surface as exceptions you can catch withtry.listenregisters callbacks and returns aStreamSubscription. It does not block, so you control the lifecycle yourself.
Stream<int> slowCount(int n) async* {
for (var i = 1; i <= n; i++) {
await Future.delayed(const Duration(milliseconds: 100));
yield i;
}
}
Future<void> main() async {
final sub = slowCount(5).listen(
(v) => print('got $v'),
onError: (Object e) => print('error: $e'),
onDone: () => print('done'),
);
await Future.delayed(const Duration(milliseconds: 250));
await sub.cancel();
}The program prints got 1 and got 2, then cancels. onDone never runs, because cancelling stops delivery before the stream finishes. You can also call sub.pause() and sub.resume(). An async* generator suspends while its subscription is paused, so it produces no extra values.
Transforming with iterable-style methods
Stream has many of the same methods as Iterable, but they return new streams (or futures for single results). Chaining is lazy, so nothing runs until someone listens.
Stream<int> numbers(int n) async* {
for (var i = 1; i <= n; i++) {
yield i;
}
}
Future<void> main() async {
final result = await numbers(10)
.where((n) => n.isOdd)
.map((n) => n * n)
.take(3)
.toList();
print(result);
}This prints [1, 9, 25]. take(3) cancels the upstream subscription after three events, so the generator stops early.
Useful futures from a stream include first, last, length, toList(), fold, and any. Stream.periodic(duration, callback) emits on a timer and never finishes by itself, so pair it with take.
Errors in streams
An error event does not necessarily end a stream, but an uncaught throw inside an async* body does. The generator stops, the error is delivered, and then the stream closes.
Stream<int> risky() async* {
yield 1;
throw Exception('boom');
}
Future<void> main() async {
try {
await for (final v in risky()) {
print(v);
}
} catch (e) {
print('caught $e');
}
}The output is 1 followed by caught Exception: boom. With await for, the first error leaves the loop and cancels the subscription. With listen, errors go to onError, and by default cancelOnError is false, so later events can still arrive from sources that continue after an error.
Single-subscription and broadcast streams
Most streams are single-subscription. They buffer events until the first listener attaches and allow only one listener for their lifetime. A broadcast stream allows many listeners but does not buffer, so a listener only sees events sent after it subscribes.
Stream<int> countTo(int n) async* {
for (var i = 1; i <= n; i++) {
yield i;
}
}
Future<void> main() async {
final s = countTo(3);
await s.toList();
try {
await s.toList();
} on StateError catch (_) {
print('second listen failed');
}
}The second toList() throws a StateError because the stream already has a listener history. To share a source, create a new stream by calling the generator again, or convert it with asBroadcastStream().
StreamController
StreamController from dart:async lets you push events into a stream manually. This is the standard bridge from callback-based code to streams.
import 'dart:async';
Future<void> main() async {
final controller = StreamController<String>();
controller
..add('a')
..add('b')
..close();
await for (final m in controller.stream) {
print(m);
}
print('closed');
}Because this is a single-subscription controller, a and b are buffered until await for starts. Here is the broadcast version:
import 'dart:async';
Future<void> main() async {
final controller = StreamController<int>.broadcast();
controller.stream.listen((v) => print('A $v'));
controller.stream.listen((v) => print('B $v'));
controller.add(1);
await controller.close();
}Both listeners print the event. A listener added after add(1) would miss it.
Common mistakes
- Listening twice to a single-subscription stream throws
StateError. UseasBroadcastStream()or recreate the stream. - Never closing a controller leaves
await forloops andonDonecallbacks waiting forever. Close it when the source is finished. - Never cancelling a subscription leaks the source, which matters for timers, sockets, and widgets that are disposed. Store the
StreamSubscriptionand callcancel()in cleanup code. - Awaiting an endless stream with
toList()orawait fornever completes. Addtake,takeWhile, orfirst. - Expecting broadcast streams to replay missed events. They do not.
- Doing slow work in the body of
await fordelays the next event. A single-subscription source buffers meanwhile, so memory can grow.
Exercises
Exercise
Write an async* function evensUpTo(int n) that yields each even number from 2 to n. Then print the sum of its values using a stream method instead of a loop.
Show answer
Use fold to add the values: Stream<int> evensUpTo(int n) async* { for (var i = 2; i <= n; i += 2) { yield i; } } Future<void> main() async { final sum = await evensUpTo(10).fold<int>(0, (a, b) => a + b); print(sum); // 30 }
Exercise
A single-subscription stream s is consumed by await s.first, and then your code calls await s.length. What happens, and how do you fix it if both reads are needed?
Show answer
The second read throws a StateError because the stream was already listened to (first listens, then cancels). Either call the generator again to get a fresh stream, or create the stream once with s.asBroadcastStream() before the first read and attach both consumers to it. Collecting once with toList() and reading from the list also works for finite streams.