DartIntermediate 2 min read

Dart stream subscriptions: cancel listeners and handle errors

Own a subscription, cancel it deliberately and distinguish an error event from stream completion.

On this page

A live progress source can outlive the screen or service currently observing it. The consumer should decide when listening ends. Cancellation is a resource decision, not just hiding a message from the UI.

Worked example

Language requirement: Dart 3.0 or later. This complete example uses browser-supported libraries.

main.dart
import 'dart:async';

Future<void> main() async {
  final source = StreamController<int>();
  final seen = <int>[];
  final subscription = source.stream.listen(
    seen.add,
    onError: (Object error) => print('Progress error: $error'),
  );
  source.add(10);
  source.add(20);
  await Future<void>.delayed(Duration.zero);
  await subscription.cancel();
  source.add(30);
  await source.close();
  print(seen.join(', '));
}

Follow the data and control flow

The subscription receives the first two queued events before it is cancelled. The later event is not delivered to that consumer. Awaiting cancellation lets cleanup finish before the caller proceeds, and closing the controller ends the producer’s lifecycle.

A single-subscription stream and a broadcast stream have different listening contracts. Broadcast is useful for multiple current listeners but is not a replay/history mechanism. Error events, normal completion and cancellation are separate outcomes that a feature should handle deliberately.

A mistake to avoid

Creating a new subscription during every UI rebuild can duplicate work and leak resources. A paused subscription may buffer events rather than stop the producer. Also avoid assuming that cancelling one observer necessarily terminates an external sensor or network source; that depends on the source’s ownership contract.

Practice and verification

Add an error event before cancellation and verify the handler receives it. Then model a consumer that stops after two values using take. Explain who closes the producer when several observers share a broadcast source.

How this topic connects

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.