Sub topic 9
Isolate.spawn and ports
This chapter assumes you know basic Dart syntax, async and await, Future, and basic streams. You will use those ideas to create an isolate that stays alive, receives work, and sends results back.
Why use `Isolate.spawn`?
Isolate.run is useful for one short task. Isolate.spawn is useful when you want a worker that can process several tasks over time.
An isolate is an independent Dart execution environment. It has its own memory heap and event loop. It cannot directly read or change variables in another isolate. Instead, isolates communicate by sending messages through ports.
A ReceivePort receives messages. A SendPort sends messages to the ReceivePort that created it.
The usual setup has two steps:
- The main isolate creates a
ReceivePortand sends itsSendPortto the worker. - The worker creates its own
ReceivePortand sends that port'sSendPortback.
After this handshake, both isolates have a port they can use to send messages.
Creating a worker
The function passed to Isolate.spawn must be a top-level or static function. It receives the value supplied as the second argument to Isolate.spawn.
The example below gives the worker the main isolate's SendPort. The worker replies with its own SendPort, then waits for commands. Each command is a record containing a job ID and a number.
import 'dart:async';
import 'dart:isolate';
void _worker(SendPort mainPort) {
final commands = ReceivePort();
// Complete the handshake by giving the main isolate this port.
mainPort.send(commands.sendPort);
commands.listen((message) {
if (message == null) {
commands.close();
return;
}
final (id, n) = message as (int, int);
var total = 0;
for (var i = 1; i <= n; i++) {
total += i;
}
mainPort.send((id, total));
});
}
Future<void> main() async {
final responses = ReceivePort();
final worker = await Isolate.spawn(_worker, responses.sendPort);
final events = StreamIterator<dynamic>(responses);
try {
// The first message is the worker's SendPort.
await events.moveNext();
final toWorker = events.current as SendPort;
toWorker.send((1, 100));
// The next message is the result record.
await events.moveNext();
final (id, result) = events.current as (int, int);
print('job $id -> $result');
// null tells the worker to stop accepting commands.
toWorker.send(null);
} finally {
await events.cancel();
responses.close();
worker.kill(priority: Isolate.beforeNextEvent);
}
}ReceivePort delivers messages asynchronously as a stream. The listen callback runs when a message arrives. Since messages can arrive in any order, a real worker often includes a job ID in every request and response. The caller can then match each result to its request.
Message design and cleanup
Messages should contain the smallest useful data. Lists, maps, strings, numbers, booleans, records, and send-port references can generally be sent. The receiving isolate gets its own transferable representation rather than shared mutable state.
A worker remains alive while its receive port is open. Define a shutdown message, close the worker's ReceivePort, and keep the Isolate handle if you may need to stop it from the outside. Calling kill is immediate cleanup, so use it when abandoning pending work.
Choosing a worker
Use a long-lived worker when startup cost would be repeated often or when many jobs share the same processing loop. For one independent calculation, Isolate.run is usually simpler. Keep the protocol small, document the message shapes, and decide how errors and shutdown are represented before adding more commands.
Exercise
Why does the worker send its own SendPort back to the main isolate?
Show answer
The main isolate needs that port to send commands to the worker's private ReceivePort. The initial port only lets the worker send messages back to the main isolate.