Sub topic 15
Streams and async generators
Assume you know Dart functions, Future, async, await, loops, and generic types. This chapter shows how to represent a sequence of values that arrives over time.
A Future<T> produces one value, or one error, later. A Stream<T> produces zero or more values over time. Streams model events such as timer ticks, search results, sensor readings, or messages from a server.
The stream model
A stream has three possible kinds of notifications:
- Data values, each with type
T. - An error, which can happen between data values.
- A done event, which means no more values will arrive.
The consumer listens to the stream. A convenient consumer is await for, which waits for each value in order.
Async generators
An asynchronous generator is a function marked async*. Its return type is Stream<T>. The yield keyword sends one value to the stream and pauses the generator until the consumer asks for another value.
Stream<int> countTo(int n) async* {
for (var i = 1; i <= n; i++) {
await Future.delayed(const Duration(milliseconds: 100));
yield i;
}
}
Future<void> main() async {
await for (final value in countTo(3)) {
print(value);
}
print('finished');
}The loop prints 1, 2, and 3, with a short delay between values. The generator does not calculate all values before the loop starts. It runs as the consumer requests values.
Use yield* to forward every event from another stream:
Stream<int> combined() async* {
yield 0;
yield* countTo(2);
yield 3;
}This stream emits 0, 1, 2, and 3.
Errors and subscriptions
An exception thrown inside an async generator becomes an error event. Handle it around the await for loop:
Stream<String> readItems() async* {
yield 'first';
throw StateError('input failed');
}
Future<void> main() async {
try {
await for (final item in readItems()) {
print(item);
}
} on StateError catch (error) {
print('Could not read items: $error');
}
}A normal stream usually supports one listener. This is called a single-subscription stream. Trying to attach a second listener can throw a StateError. Use a broadcast stream when several independent listeners must receive the same events, but remember that late listeners may miss earlier events.
Common mistakes
- Use
asyncandFuture<T>for one eventual result. - Use
async*andStream<T>for repeated results. - Use
yieldfor one event andyield*to forward another stream. - Do not return a list when callers need values as they become available.
- Cancel a
StreamSubscriptionwhen a long-lived listener is no longer needed.
Exercise
Which keyword should a function use when it produces several values over time, and how does a caller consume those values?
Show answer
The function uses async* and returns Stream<T>. The caller can consume it with await for, or listen with a stream subscription.