Sub topic 12
From Futures to Streams: `await for`
Prerequisites: you should know Dart functions, generics, callbacks, Future, async, await, and how to run a Dart program with dart run.
A Future<T> represents one result that arrives later. A Stream<T> represents zero or more results that arrive over time. Use a stream when values can continue arriving, such as timer ticks, search results, file data, or messages from a socket.
await for reads a stream one value at a time. Each iteration waits until the next value arrives. The loop finishes when the stream sends its done event.
flowchart TD
A[Stream starts] --> B[Value arrives]
B --> C[await for runs loop body]
C --> D{More values?}
D -->|Yes| B
D -->|No| E[Loop finishes]
D -->|Error| F[try/catch handles error]caption: How await for consumes a stream alt: A flowchart showing values arriving repeatedly, being handled by an await for loop, and ending when the stream is done.
Creating a stream with `async*`
An async* function is an asynchronous generator. It returns a Stream<T> instead of a Future<T>. The yield keyword sends one value to the stream's listener.
Stream<int> ticks(int count) async* {
for (var i = 1; i <= count; i++) {
await Future<void>.delayed(const Duration(milliseconds: 200));
yield i;
}
}
Future<void> main() async {
await for (final tick in ticks(3)) {
print('tick $tick');
}
print('stream complete');
}The function pauses at each await. When the delay finishes, yield sends the next integer. The loop prints each value as it arrives:
tick 1
tick 2
tick 3
stream completeThe loop itself must be inside an async function because it waits for asynchronous values.
Handling errors and cleanup
A stream can finish normally or finish with an error. Put await for inside try and catch when the stream may fail.
Stream<String> messages() async* {
yield 'connected';
yield 'received data';
throw StateError('connection lost');
}
Future<void> main() async {
try {
await for (final message in messages()) {
print(message);
}
} on StateError catch (error) {
print('Stream failed: $error');
} finally {
print('listener finished');
}
}The finally block runs whether the stream completes normally or throws. If you need to stop reading early, use break. Dart then cancels the stream subscription, which tells the stream that this listener no longer needs values.
Common stream choices
| Stream kind | Meaning | Typical use |
|---|---|---|
| Single-subscription | One listener can consume the stream | A file download or one operation |
| Broadcast | Multiple listeners can listen at the same time | Application events or sensors |
| Periodic | Emits values at regular intervals | Clocks, polling, and timers |
A single-subscription stream usually cannot be listened to twice. If two parts of an application need the same events, create a broadcast stream or publish the events through a suitable shared source. Do not convert every stream to broadcast automatically. Broadcast streams can drop events for listeners that join late.
`await for` compared with `listen`
You can consume a stream with listen, which uses callbacks:
ticks(3).listen(
(value) => print('tick $value'),
onDone: () => print('finished'),
onError: (error) => print('error: $error'),
);Use await for when the surrounding logic is naturally sequential and needs try, catch, finally, break, or return. Use listen when you need a long-lived subscription, several callbacks, or direct control over cancellation.
Exercise
What does await for do when the stream sends its done event, and how can you handle a stream error?
Show answer
The loop ends when the done event arrives. Put the loop inside try and catch, such as try { await for (final value in stream) { ... } } catch (error) { ... }.