Dart Medium · Lesson 1 · On the house

Streams and await for

Stream<T>, async* generators, yield, await for, and listen. Lesson 1 is free — on the house.

Lessons · Dart Medium · Lesson 1 of 10 · On the house

Streams and await for

Stream<T>, async* generators, yield, await for, and listen.

Illustration for Dart
Lesson 1 is on the house.

A Stream<T> delivers many values over time, where a Future delivers one. Consume it with await for (final x in stream) inside an async function, or with stream.listen(onData).

async* functions return a Stream; yield v emits one value and yield* other forwards another stream. The body runs only while someone listens.

Streams support pipelines like iterables: where, map, take, asyncMap (await per item) and fold. stream.toList() collects everything into a Future.

A single-subscription stream (the default) allows one listener. asBroadcastStream() or StreamController.broadcast() allows many listeners, but late listeners miss earlier events.

await for ends when the stream closes. A break cancels the subscription, which stops the generator.

async* stream

Stream<int> countdown(int from) async* {
  for (var i = from; i > 0; i--) {
    yield i;
  }
}

Future<void> main() async {
  await for (final n in countdown(3)) {
    print(n);
  }
  final evens = await countdown(6).where((n) => n.isEven).toList();
  print(evens);
}
Match this when you type.

Quiz

What does an async* function return?

Quiz

What does yield do inside async*?

Quiz

What does the evens line print?

Quiz

What happens to the generator when await for hits break?

Check

Match the still for: Streams and await for.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.