magic_isolate 0.0.2
magic_isolate: ^0.0.2 copied to clipboard
A lightweight wrapper around Dart isolates that removes the SendPort/ReceivePort handshake boilerplate — spawn, communicate, and close isolates with one simple object.
magic_isolate #
A lightweight wrapper around Dart isolates that removes the
SendPort/ReceivePort handshake boilerplate. Spawn an isolate, send it
work, and get results back — all through one simple object.
Features #
- One call (
MagicIsolate.spawn) handles spawning, the handshake, and readiness — no manualReceivePort/SendPortjuggling. - Two ways to get results back:
onMessage— a persistent listener for ongoing communication.request()— aFuture-based, one-send-one-result style.
sendRequests— queue a batch of messages to be sent immediately after the isolate is ready.closeOn— configurable shutdown sentinel, with a cleanclose()that waits for the worker to acknowledge before killing the isolate.MagicWorker.listen()on the worker side removes the matching boilerplate there too — just return a value from your handler and it's sent back automatically.
Getting started #
Add the package to your pubspec.yaml:
dependencies:
magic_isolate: ^0.0.1
Usage #
Define your worker as a top-level function (a requirement of
Isolate.spawn itself):
import 'dart:isolate';
import 'package:magic_isolate/magic_isolate.dart';
void sortWorker(SendPort mainSendPort) {
MagicWorker.listen(mainSendPort, (message) {
final data = List<double>.from(message as List);
data.sort();
return data.last;
});
}
Request/response style:
final magicIsolate = await MagicIsolate.spawn(worker: sortWorker);
final biggest = await magicIsolate.request([10.0, 12.0, 45.0, 34.0, 89.0]);
print(biggest); // 89.0
await magicIsolate.close();
Persistent listener + startup batch:
final magicIsolate = await MagicIsolate.spawn(
worker: sortWorker,
onMessage: (message) => print('results => $message'),
closeOn: 'close',
sendRequests: [
[10.0, 12.0, 45.0, 34.0, 89.0],
'close',
],
);
See the example for a full runnable demo of both styles.
Additional information #
Contributions and issues are welcome on the GitHub repository.