Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 61 ยท Asynchronous Dart

Streams

Learn Dart streams: single-subscription and broadcast streams, listen and await for, StreamController, async* generators, transformations and cancelling subscriptions.

A Future delivers one value later. A Stream<T> delivers a sequence of values over time: bytes arriving from a file, messages from a server, taps on a button, ticks of a timer. A stream can produce data events, an error event, and finally a "done" event that says nothing more will come.

You can think of a Stream as an asynchronous Iterable: with an iterable you pull values when you ask; with a stream the values arrive when they are ready. The Dart code is read-only. The TypeScript stand-ins use async generators and for await, which map very closely onto async* and await for.

Consuming a stream

There are two ways to read a stream. The first is listen, which registers callbacks:

DART
import 'dart:async';

void main() {
  Stream<int> ticks = Stream.periodic(const Duration(milliseconds: 100), (i) => i).take(3);

  StreamSubscription<int> sub = ticks.listen(
    (value) => print('tick $value'),
    onError: (Object e) => print('error: $e'),
    onDone: () => print('done'),
  );
  // later, if you lose interest: sub.cancel();
}

This prints tick 0, tick 1, tick 2 and then done. The StreamSubscription returned by listen lets you pause(), resume() and cancel().

The second way reads far more like normal code: await for inside an async function.

DART
Future<void> main() async {
  var ticks = Stream.periodic(const Duration(milliseconds: 100), (i) => i).take(3);

  var total = 0;
  await for (final value in ticks) {
    print('got $value');
    total += value;
  }
  print('total: $total');        // total: 3, printed after the stream ends
}

The loop waits for each event, runs the body, and finishes when the stream is done. If the stream emits an error, await for throws it, so you can wrap the loop in try/catch. Use break to stop early; leaving the loop cancels the subscription.

Streams also come with the same helpers you know from iterables: map, where, take, skip, expand, and futures-returning summaries such as first, last, length, toList(), fold and any. For example, await stream.where((n) => n.isEven).toList().

Generating a stream with async*

An async* function is a generator. Instead of returning one value it yields many, and the caller sees a Stream:

DART
Stream<int> countdown(int from) async* {
  for (var i = from; i > 0; i--) {
    await Future.delayed(const Duration(milliseconds: 50));
    yield i;                       // emit one event
  }
}

Stream<int> twice(Stream<int> source) async* {
  await for (final n in source) {
    yield n;
    yield n;
  }
}

Stream<String> tree(int depth) async* {
  yield 'node $depth';
  if (depth > 0) {
    yield* tree(depth - 1);        // yield* forwards every event of another stream
  }
}

The body of an async* function does not start until somebody listens. It also pauses at each yield if the listener is slow, which gives you natural back-pressure: the producer cannot run far ahead of the consumer. This is the easiest way to write a stream by hand.

TypeScript Generating and consuming a stream (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

StreamController

When events come from callbacks (a button, a socket, your own code) you need a way to push them into a stream. That is the job of StreamController. You add events on the controller and hand out its stream:

DART
import 'dart:async';

Future<void> main() async {
  var controller = StreamController<String>();

  controller.stream.listen(
    (msg) => print('received: $msg'),
    onError: (Object e) => print('error event: $e'),
    onDone: () => print('closed'),
  );

  controller.add('hello');
  controller.add('world');
  controller.addError(StateError('oops'));     // an error event; the stream continues
  await controller.close();                    // done event
}

Always close() the controller when you are finished, and keep the controller private: expose only its stream so outside code cannot add events. A controller has two useful callbacks, onListen (start producing when someone subscribes) and onCancel (stop and free resources when they leave). Adding to a closed controller throws a StateError.

Single-subscription and broadcast streams

By default a stream can have one listener for its whole life. Listening a second time throws Bad state: Stream has already been listened to. This design fits streams that carry data you must not lose, such as file bytes: events wait until a listener arrives.

When several parts of a program should receive the same events, make a broadcast stream:

DART
Future<void> main() async {
  var controller = StreamController<int>.broadcast();

  controller.stream.listen((n) => print('A: $n'));
  controller.stream.listen((n) => print('B: $n'));

  controller.add(1);                     // both A and B see it
  controller.add(2);
  await controller.close();

  // An existing single-subscription stream can be converted:
  var shared = Stream.fromIterable([1, 2, 3]).asBroadcastStream();
}

A broadcast stream does not buffer: events fired when nobody is listening are lost, and a late listener sees only new events. There is also no back-pressure. Mouse clicks and UI events are typical broadcast streams; file reads and HTTP bodies are single-subscription.

flowchart LR
    P["producer<br/>add / yield"] --> S["Stream"]
    S -->|"single subscription"| L1["one listener"]
    S -->|"broadcast"| L2["listener A"]
    S -->|"broadcast"| L3["listener B"]

A single-subscription stream serves one listener and waits for it; a broadcast stream serves any number of listeners but forgets events nobody heard.

TypeScript A tiny broadcast controller (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Transforming streams

Streams chain just like lists. Each method returns a new stream:

DART
Future<void> main() async {
  var words = Stream.fromIterable(['dart', 'stream', 'async', 'flutter']);

  var result = await words
      .where((w) => w.length > 4)
      .map((w) => w.toUpperCase())
      .toList();
  print(result);                          // [STREAM, FLUTTER]

  var lengths = await Stream.fromIterable([1, 2, 3, 4])
      .asyncMap((n) async => n * 10)      // the function may be async
      .fold<int>(0, (sum, n) => sum + n);
  print(lengths);                         // 100
}

For reusable conversions there is stream.transform(...) with a StreamTransformer, such as utf8.decoder or const LineSplitter() from dart:convert. Most of the time map, where and an async* helper are enough.

Common mistakes

  • Listening twice to a single-subscription stream. Use asBroadcastStream() or StreamController.broadcast() if you need several listeners.
  • Forgetting to cancel a subscription (or close a controller). The program may keep running, and memory may leak.
  • Awaiting a stream that never ends (await stream.toList() on a periodic stream). Add take(n) or a takeWhile.
  • Expecting broadcast streams to remember earlier events.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the difference between a Future and a Stream?

    A Future completes once, with a value or an error. A Stream can emit any number of data events and then a done event.
  2. 2. What does yield do inside an async* function?

    Each yield sends a value to the listener, and the function continues. yield* forwards all events of another stream.
  3. 3. What happens when you call listen twice on an ordinary (single-subscription) stream?

    A single-subscription stream allows one listener. For several listeners use a broadcast stream.
  4. 4. A broadcast stream emits an event while nobody is listening. What happens to it?

    Broadcast streams do not buffer. A listener sees only the events fired after it subscribed.
  5. 5. How do you read every event of a stream in straight-line code?

    await for waits for each event and ends when the stream is done. A plain for-in works on Iterables, not on Streams.

Summary

  • A Stream<T> is an asynchronous sequence of data events, errors and a final done event.
  • Read it with listen (callbacks, returns a cancellable StreamSubscription) or await for (straight-line code).
  • async* plus yield and yield* generate streams, with natural back-pressure.
  • StreamController pushes events from callbacks; always close() it and expose only its stream.
  • Streams are single-subscription by default; broadcast streams allow many listeners but do not buffer.
  • Streams support map, where, take, asyncMap, fold, toList and transform.

Next, learn how Dart schedules all this work in The Event Loop, Microtasks and Zones.