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
async*builds aStream;yieldemits each value.await forloops as values arrive.- Stream getters like
.lengthare futures themselves.
Keywords and builtins used here
Stringasyncawaitconstfinalforinvoidyield
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.
Step 2 of 3 in Async, step 23 of 27 in Language basics.