pub package github stars license MIT Build Status Code Coverage

A wrapper class for Isolate that exposes a communication channel using a Stream.

API Reference

Basic Usage

To use, call StreamIsolate.spawn with the same types of arguments passed to Isolate.spawn. You can then use the returned instance to subscribe to events published by the isolate:

final streamIsolate = await StreamIsolate.spawn(doWork);
await for (final i in streamIsolate.stream) {
  print(i);
}
Stream<int> doWork() async* {
  yield 1;
  yield 2;
  yield 3;
  yield 4;
  yield 5;
}

Bidirectional Communication

You can also call BidirectionalStreamIsolate.spawn (or StreamIsolate.spawnBidirectional) to create an isolate that exposes an additional communication stream for sending messages to the instance:

final streamIsolate = await BidirectionalStreamIsolate.spawn(doWork);
await for (final i in streamIsolate.stream) {
  print(i);
  streamIsolate.send('received');
}
Stream<int> doWorkWithListener(Stream<String> inc) async* {
  inc.listen((msg) => print('from main: $msg'));

  yield 1;
  yield 2;
  yield 3;
  yield 4;
  yield 5;
}

Passing Initial Arguments

You can optionally send an argument that gets passed to the thread function when it first runs. This is done using the StreamIsolate.spawnWithArgument and BidirectionalStreamIsolate.spawnWithArgument methods.

class IsolateArgs {
  final int index;
  final String name;

  const IsolateArgs(this.index, this.name);
}

...

final args = IsolateArgs(1, 'Worker Isolate 1');
final streamIsolate = await StreamIsolate.spawnWithArgument(doWork, argument: args);
await for (final i in streamIsolate.stream) {
  print(i);
  streamIsolate.send('received');
}
Stream<int> doWorkWithListener(Stream<String> inc, IsolateArgs args) async* {
  print('Starting worker isolate ${args.name}, Index: ${args.index}');

  yield 1;
  yield 2;
  yield 3;
  yield 4;
  yield 5;
}

Examples

  • Vanilla - A simple example of using stream isolates.
  • RxDart - An example of using RxDart to manage the isolate streams.
  • Multithreaded Noise - An example of a Flutter app using stream isolates to generate animated Perlin Noise.

Libraries

stream_isolate