← Flutter / Dart

Flutter / Dart · 22 / 24

Streams and isolates for background work

Process an event stream, offload computation and cancel the subscription deliberately.

  • Large
  • Advanced
  • 90 min

Prerequisites: Null safety, errors and Future

In this tutorial
  1. Define the boundary
  2. Set up the learning project
  3. Trace the successful outcome
  4. Observe failures deliberately
  5. Solve the extension
  6. Compare the solution
  7. Exercise and solution
  8. Project context and sources

Download learning package

Setup and verification

Flutter 3.41.5 or newer with Dart 3.11. Python 3 is also required for the common verification entry point. Extract the learning package into a new folder and run python3 run_checks.py there. The script copies the included files into a temporary learning directory. It verifies the example and then the supplied solution there, preserving the original files. Required packages are downloaded on the first run.

Verified on 2026-10-20 on Linux x86_64. Check result ordering, error propagation and subscription cancellation. Cancelling a subscription does not automatically stop every calculation already in progress.

Streams deliver multiple results over time. An isolate has its own execution context. This example combines them without a Flutter interface. An event triggers a calculation. The test observes a result and then verifies that cancellation prevents further delivery. Isolate.run handles a finite task but is not a general hard-cancellation contract.

Package contents and individual files

01Define the boundary

A stream delivers events over time. asyncMap waits for each event to be processed. Isolate.run moves CPU work out of the calling isolate. Values crossing that boundary must be transferable.

lib/model.dart · dartOpen file
import 'dart:isolate';

Future<int> computeTotal(List<int> values) => Isolate.run(() {
  var sum = 0;
  for (final value in values) {
    if (value < 0) throw ArgumentError('Negative reading');
    sum += value;
  }
  return sum;
});
Stream<int> totals(Stream<List<int>> input) => input.asyncMap(computeTotal);

02Set up the learning project

Direct dependencies are pinned. Extract all files together and run flutter pub get. Do not use an existing app database for tests. Tests create and clean up their own data.

pubspec.yaml · yamlOpen file
name: learning_example
publish_to: none
environment:
  sdk: ">=3.11.0 <4.0.0"
dependencies:
  flutter:
    sdk: flutter
  flutter_riverpod: 3.3.1
  drift: 2.33.0
  path_provider: 2.1.5
dev_dependencies:
  flutter_test:
    sdk: flutter
flutter:
  uses-material-design: true

03Trace the successful outcome

Check result ordering, error propagation and subscription cancellation. Cancelling a subscription does not automatically stop every calculation already in progress.

test/model_test.dart · dartOpen file
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:learning_example/model.dart';

void main() {
  test('delivers totals and cancels the source subscription', () async {
    final source = StreamController<List<int>>();
    final seen = <int>[];
    final first = Completer<void>();
    final subscription = totals(source.stream).listen((value) {
      seen.add(value);
      first.complete();
    });
    source.add([1, 2, 3]);
    await first.future;
    await subscription.cancel();
    expect(source.hasListener, isFalse);
    source.add([99]);
    await source.close();
    expect(seen, [6]);
  });
  test('worker errors stay errors', () async {
    await expectLater(computeTotal([-1]), throwsArgumentError);
  });
}

Run / check

flutter pub get
flutter test
Expected result

Check result ordering, error propagation and subscription cancellation. Cancelling a subscription does not automatically stop every calculation already in progress.

04Observe failures deliberately

Change an expected number or state in the test. flutter test must fail. Restore the correct expectation afterwards. Distinguish a domain failure from a missing plugin or development environment.

05Solve the extension

Verify empty input and two lists arriving in sequence.

06Compare the solution

An empty list sums to zero. asyncMap preserves event order while awaiting each calculation. Very large lists additionally require considering transfer cost and bounded queues.

Expected result

flutter test passes for the original example and the extended solution.

Your exercise

Verify empty input and two lists arriving in sequence.

Show the solution and explanation

An empty list sums to zero. asyncMap preserves event order while awaiting each calculation. Very large lists additionally require considering transfer cost and bounded queues.

solution/model_test.dart · dartOpen file
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:learning_example/model.dart';

void main() {
  test('empty and ordered input', () async {
    expect(
      await totals(
        Stream.fromIterable([
          <int>[],
          [4, 5],
        ]),
      ).toList(),
      [0, 9],
    );
  });
  test('delivers totals and cancels the source subscription', () async {
    final source = StreamController<List<int>>();
    final seen = <int>[];
    final first = Completer<void>();
    final subscription = totals(source.stream).listen((value) {
      seen.add(value);
      first.complete();
    });
    source.add([1, 2, 3]);
    await first.future;
    await subscription.cancel();
    expect(source.hasListener, isFalse);
    source.add([99]);
    await source.close();
    expect(seen, [6]);
  });
  test('worker errors stay errors', () async {
    await expectLater(computeTotal([-1]), throwsArgumentError);
  });
}

Project context and sources

This independent learning project explores a topic in this technology area. Project references provide a pinned revision as architectural context. They do not imply that every library or feature introduced here is already used in that application.