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.
example/magic_isolate_example.dart
import 'dart:isolate';
import 'package:magic_isolate/magic_isolate.dart';
/// The worker function that runs inside the spawned isolate.
///
/// Must be a top-level (or static) function — this is a requirement of
/// `Isolate.spawn` itself, not of this package.
void sortWorker(SendPort mainSendPort) {
MagicWorker.listen(mainSendPort, (message) {
final data = List<double>.from(message as List);
data.sort();
return data.last;
});
}
Future<void> main() async {
// --- Style 1: request/response ---
final magicIsolate = await MagicIsolate.spawn(worker: sortWorker);
final biggest = await magicIsolate.request([10.0, 12.0, 45.0, 34.0, 89.0]);
print('biggest (via request) => $biggest');
await magicIsolate.close();
// --- Style 2: persistent onMessage listener + startup batch ---
final magicIsolate2 = await MagicIsolate.spawn(
worker: sortWorker,
onMessage: (message) => print('results => $message'),
closeOn: 'close',
sendRequests: [
[10.0, 12.0, 45.0, 34.0, 89.0],
'close',
],
);
// Give the isolate a moment to process the queued sendRequests before
// the program exits.
await Future.delayed(const Duration(milliseconds: 300));
print('isolate 2 closed: ${magicIsolate2.isClosed}');
}