typestar

Streams and async* in Dart

A generator that emits over time; await for consumes in order.

// async* builds a Stream; yield emits into it as values are ready.
Stream<String> radioCalls() async* {
  final calls = ['curlew west', 'two egrets', 'harrier over reeds'];
  for (final call in calls) {
    await Future.delayed(const Duration(milliseconds: 20));
    yield call;
  }
}

Future<void> main() async {
  // await for consumes the stream in arrival order.
  await for (final call in radioCalls()) {
    print('Radio: $call');
  }
  final count = await radioCalls().length;
  print('$count calls this watch');
}

How it works

  1. async* builds a Stream; yield emits each value.
  2. await for loops as values arrive.
  3. Stream getters like .length are futures themselves.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
494
Tokens
105
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 97 seconds.

Type this snippet

Step 2 of 3 in Async, step 23 of 27 in Language basics.

← Previous Next →