Skip to content

Instantly share code, notes, and snippets.

@guilherme-v
Last active July 5, 2020 21:59
Show Gist options
  • Save guilherme-v/a6c0cb24ebd60f5ee99bbb5e8ef6a3df to your computer and use it in GitHub Desktop.
Save guilherme-v/a6c0cb24ebd60f5ee99bbb5e8ef6a3df to your computer and use it in GitHub Desktop.
import 'dart:async';
import 'dart:io';
import 'dart:isolate';
main(List<String> args) async {
stdout.writeln("isolate running the 'main' method is called: " +
Isolate.current.debugName);
// creates a port to receive messages on MainIsolate
final mainControlPort = ReceivePort();
// Spawns reates a new isolate
// Once it's start, it will run the "timerTick" function and
// the param will be the "mainControlPort.sendPort".
// This away it can send messages back to the "parent" main Isolate when needed
Isolate timerIsolate;
timerIsolate = await Isolate.spawn(
timerTick,
mainControlPort.sendPort,
debugName: "TimerIsolate",
);
// mainControlPort is a normal stream, transform it in a broadcast one
// this way we can listen it in more than one place: (1) and (2)
final streamOfMesssage = mainControlPort.asBroadcastStream();
// (1)
// Send a message to TimerIsolate start itself
stdout.writeln(Isolate.current.debugName + " asking TimerIsolate to start");
SendPort timer = await streamOfMesssage.first;
timer.send("start");
// (2)
// Keep listening messages from TimerIsolate until we receive 10 messages
// then kill both "MainIsolate" and "TimerIsolate"
var counter = 0;
streamOfMesssage.listen(
(message) {
counter++;
if (counter == 10) {
stdout.writeln("finishing timer...");
timerIsolate.kill();
stdout.writeln("finishing main...");
Isolate.current.kill();
} else {
stdout.writeln(message);
}
},
);
}
void timerTick(SendPort mainPort) async {
final timerControlPort = ReceivePort();
stdout.writeln(Isolate.current.debugName + " started");
mainPort.send(timerControlPort.sendPort);
await timerControlPort.firstWhere((message) => message == "start");
stdout.writeln(Isolate.current.debugName + " will start sending messages...");
Timer.periodic(Duration(seconds: 1), (timer) {
mainPort.send(DateTime.now().toIso8601String());
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment