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
Replay: real traced execution (multi-file project)
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');
}
total ← 0
7Future<void> main() async {8 var total = 0;9 await for (var n in countDown()) {values this step0totalyield ← 3
1Stream<int> countDown() async* {2 yield 3;3 yield 2;values this step3yieldstream event ← n = 3
8var total = 0;9await for (var n in countDown()) {10 total += n;values this stepn = 3stream eventtotal ← 3
9await for (var n in countDown()) {10 total += n;11}values this step0 → 3total3nyield ← 2
2yield 3;3yield 2;4yield 1;values this step2yieldstream event ← n = 2
8var total = 0;9await for (var n in countDown()) {10 total += n;values this stepn = 2stream eventtotal ← 5
9await for (var n in countDown()) {10 total += n;11}values this step3 → 5total2nyield ← 1
3 yield 2;4 yield 1;5}values this step1yieldstream event ← n = 1
8var total = 0;9await for (var n in countDown()) {10 total += n;values this stepn = 1stream eventtotal ← 6
9await for (var n in countDown()) {10 total += n;11}values this step5 → 6total1nstream event ← done (closed)
8var total = 0;9await for (var n in countDown()) {10 total += n;values this stepdone (closed)stream eventprint('countdown sum = $total');
11 }12 print('countdown sum = $total');13}outputcountdown sum = 6values this step6total
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.