Sub topic 12
From Futures to Streams: await for
A Future delivers one value later. A Stream delivers zero or more values over time, followed by a "done" signal. This chapter shows how await for extends the await idea from one value to many, and how errors, cancellation, and stream types behave in practice.
This chapter assumes you can write async functions, use await, and handle Future errors with try/catch. It also assumes you know the event loop model from earlier chapters.
What a Stream is
A Stream is a sequence of asynchronous events. Each event is one of three things:
- A data event carrying a value.
- An error event carrying an exception and a stack trace.
- A done event, which signals that no more events will come.
Typical sources are keystrokes, sensor readings, bytes read from a file, messages from a WebSocket, or the periodic ticks of a timer. In each case you do not know when the next value arrives, or how many will arrive.
The table shows how the two types compare.
| Row | Future<T> | Stream<T> |
|---|---|---|
| Values delivered | Exactly one, or one error | Zero or more, plus errors |
| Completion | The Future completes once | A done event ends the stream |
| Consumed with | `await`, `then` | `await for`, `listen` |
| Produced with | `async`, `Completer` | `async*`, `StreamController` |
Consuming a stream with await for
await for looks like a normal for-in loop. It waits for each event, runs the body with the value, and then waits for the next event. The loop ends when the stream sends its done event.
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 t in ticks(3)) {
print('tick $t');
}
}This prints tick 1, tick 2, and tick 3 at about 200 ms intervals. await for is only legal inside a function marked async or async*. The enclosing function is suspended at each wait, so the event loop stays free to run other work.
The function ticks is an asynchronous generator. Its async* marker means it returns a Stream. Each yield emits a data event, and when the function body ends, the stream sends done. Inside an async* function you can also use await, as ticks does with Future.delayed.
Which events the loop sees
The loop body runs only for data events. An error event is thrown at the await for statement, and the done event ends the loop normally. This means the loop is a faithful analog of a sequence of await expressions, where each step can produce a value or throw.
Creating streams
You will meet streams from libraries far more often than you create them. Still, the common ways to build one are worth knowing.
Stream.fromIterable(list)emits each element of an existing collection.Stream.periodic(duration, computation)emits a value on a timer. It never ends on its own.async*functions emit values withyield.StreamControllerlets any code push events into a stream by hand.
Stream.periodic pairs well with the stream methods take, where, and map, which return new streams:
Future<void> main() async {
final evens = Stream.periodic(
const Duration(milliseconds: 100),
(i) => i,
).where((n) => n.isEven).take(3);
await for (final n in evens) {
print(n);
}
}The output is 0, 2, 4. Without take(3) the loop would never finish, because a periodic stream never sends done.
Streams also offer Future-returning helpers for common shapes: first, last, length, toList(), and fold. Each one consumes the stream and returns a Future with the result. For example, await Stream.fromIterable([1, 2, 3]).toList() gives [1, 2, 3]. Never call toList() on an infinite stream, because the Future would never complete and memory would grow.
Errors in a stream
A stream can send an error event and still continue. When an async* function throws, however, the error is sent and the stream then closes.
Stream<int> flaky() async* {
yield 1;
yield 2;
throw StateError('sensor failed');
}
Future<void> main() async {
try {
await for (final v in flaky()) {
print('got $v');
}
} on StateError catch (e) {
print('stream failed: ${e.message}');
}
}The output is got 1, got 2, and then stream failed: sensor failed. You handle stream errors with the same try/catch/finally you use around await. An uncaught error in the loop propagates out of the enclosing async function and completes its Future with that error.
Note that the try surrounds the whole await for. A try inside the body would only catch exceptions thrown by your own body code, not errors arriving from the stream.
Stopping early and cancellation
Leaving the loop early with break, return, or an exception cancels the underlying subscription. This tells the stream that nobody is listening anymore, so it can release resources such as timers, sockets, or file handles.
Stream<int> counter() async* {
try {
var i = 0;
while (true) {
await Future<void>.delayed(const Duration(milliseconds: 100));
yield i++;
}
} finally {
print('counter cleaned up');
}
}
Future<void> main() async {
await for (final n in counter()) {
print(n);
if (n == 2) break;
}
print('loop exited');
}This program prints 0, 1, 2, then the cleanup message, then loop exited. The break cancels the subscription, and the generator's finally block runs. Without break, this loop would run forever.
Single-subscription and broadcast streams
Streams come in two kinds, and the difference causes a common runtime error.
| Row | Single-subscription | Broadcast |
|---|---|---|
| Listeners allowed | One, for the whole life of the stream | Any number, at any time |
| Events before a listener attaches | Buffered until someone listens | Lost |
| Typical use | File reads, HTTP bodies, `async*` | UI events, app-wide notifications |
Most streams are single-subscription, including those from async* functions and StreamController(). Listening to one a second time throws a StateError with the message "Stream has already been listened to." If several consumers need the same events, create the stream with StreamController.broadcast(), or call asBroadcastStream() on an existing stream.
Two consequences of broadcast behavior are worth knowing:
- A late listener misses everything emitted before it subscribed.
- A broadcast stream does not wait for slow listeners, so an
await forbody that takes a long time can fall behind. The events are delivered when the loop returns, but the stream does not pause for it.
Pushing events with StreamController
A StreamController is the stream counterpart of Completer. It gives you a stream to hand to consumers and methods like add, addError, and close to send events.
import 'dart:async';
Future<void> main() async {
final controller = StreamController<String>();
controller.add('first');
controller.add('second');
controller.close();
await for (final message in controller.stream) {
print(message);
}
}Because this is a single-subscription stream, the two events are buffered until the loop starts listening. The loop prints first and second, then sees the done event from close() and exits. If you forget to call close(), the loop waits forever and the program never finishes.
await for versus listen
await for is not the only way to consume a stream. The listen method registers callbacks and returns immediately, without suspending anything.
import 'dart:async';
Future<void> main() async {
final done = Completer<void>();
Stream.fromIterable([1, 2, 3]).listen(
(value) => print('value $value'),
onError: (Object e) => print('error $e'),
onDone: done.complete,
);
print('listen returned');
await done.future;
}listen returned prints first, because listen does not wait. The values follow once the event loop delivers them. The returned StreamSubscription can pause, resume, and cancel.
Choose between the two like this:
- Use
await forwhen the code reads best as a sequence of steps, with the function waiting until the stream ends. Errors go totry/catch. - Use
listenwhen you want to start listening and continue with other work, when you need to pause or cancel from outside, or when you manage several streams at once.
A related trap: one await for loop blocks the rest of its function until the stream ends. If you write two loops in a row over infinite streams, the second never starts. Run them concurrently by wrapping each loop in its own async function and combining the returned Futures with Future.wait, or by using listen.
Common mistakes
- Calling an
async*function and ignoring the result. Nothing runs until something listens, because the body of anasync*generator starts on the first listen. - Forgetting that
Stream.periodicnever ends, and then waiting on it withtoList()or an unboundedawait for. - Putting
asyncwhere you needasync*. Anasyncfunction returns aFutureand cannot useyield. Anasync*function returns aStream. - Listening twice to a single-subscription stream.
- Using a
StreamControllerand never closing it.
Exercise
A function returns Stream<int> from a StreamController() and you write two separate await for loops over controller.stream, one after the other, in the same async function. What happens, and how would you let both consumers receive the events?
Show answer
The first loop is the only listener a single-subscription stream allows, so the second loop throws a StateError ("Stream has already been listened to") when it starts. To serve several consumers, create the controller with StreamController.broadcast() (or call asBroadcastStream() on the stream). Remember that a broadcast stream drops events sent before a listener subscribes, so the listeners must be attached before the events are added.
Exercise
Write an async* function countDown(int from) that yields from, from - 1, down to 1 with a 100 ms delay before each value, and a main that prints each value with await for and stops after printing 2 using break.
Show answer
Stream<int> countDown(int from) async* { for (var i = from; i >= 1; i--) { await Future<void>.delayed(const Duration(milliseconds: 100)); yield i; } } Future<void> main() async { await for (final n in countDown(5)) { print(n); if (n == 2) break; } } With from set to 5 this prints 5, 4, 3, 2. The break cancels the subscription, so the generator stops before yielding 1.