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');
}
  1. total ← 0

    7Future<void> main() async {8  var total = 0;9  await for (var n in countDown()) {
    values this step0total
  2. yield ← 3

    1Stream<int> countDown() async* {2  yield 3;3  yield 2;
    values this step3yield
  3. stream event ← n = 3

    8var total = 0;9await for (var n in countDown()) {10  total += n;
    values this stepn = 3stream event
  4. total ← 3

    9await for (var n in countDown()) {10  total += n;11}
    values this step0 3total3n
  5. yield ← 2

    2yield 3;3yield 2;4yield 1;
    values this step2yield
  6. stream event ← n = 2

    8var total = 0;9await for (var n in countDown()) {10  total += n;
    values this stepn = 2stream event
  7. total ← 5

    9await for (var n in countDown()) {10  total += n;11}
    values this step3 5total2n
  8. yield ← 1

    3  yield 2;4  yield 1;5}
    values this step1yield
  9. stream event ← n = 1

    8var total = 0;9await for (var n in countDown()) {10  total += n;
    values this stepn = 1stream event
  10. total ← 6

    9await for (var n in countDown()) {10  total += n;11}
    values this step5 6total1n
  11. stream event ← done (closed)

    8var total = 0;9await for (var n in countDown()) {10  total += n;
    values this stepdone (closed)stream event
  12. print('countdown sum = $total');

    11  }12  print('countdown sum = $total');13}
    outputcountdown sum = 6
    values 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.