Async and Practical
Async Generators
async* and yield
An async* function is a stream generator: each yield emits one value, and the function pauses until the consumer asks for the next. await for reads those values in order, one per iteration, and ends when the generator returns.
Program
Play the program to consume three yielded values and sum them.
stream_await_for.dart
Stream<int> countDown() async* {
yield 3;
yield 2;
yield 1;
}
Future<void> main() async {
var total = 0;
await for (var n in countDown()) {
total += n;
}
print('countdown sum = $total');
}
async*
An `async*` function is a stream generator; each `yield` emits one value, then it pauses.
await for
`await for (var n in countDown())` resumes the generator and binds each yielded value to `n` in order.
finite stream
When the generator returns, the stream closes and the `await for` loop ends.