cross_isolate_messenger 0.0.2
cross_isolate_messenger: ^0.0.2 copied to clipboard
A lightweight utility for message passing between Dart isolates with persistent storage using SharedPreferences. Designed for native Flutter apps.
๐จ Cross Isolate Messenger #
Cross Isolate Messenger is a lightweight Dart utility for reliable message passing and durability across Flutter isolates.
It ensures that messages are not lost during app lifecycle events by persisting them using SharedPreferences, and allows seamless replay and garbage collection.
โจ Features #
- ๐จ Reliable queue: Ensures messages sent from background isolates reach the UI.
- ๐ Replay & persistence: Messages are stored and replayed until acknowledged.
- ๐งผ Garbage collection: Acknowledged messages are purged automatically.
- ๐ Stream-based: UI receives messages via
Stream<T>. - ๐ IsolateNameServer: Automatically manages isolate communication.
๐งฉ Requirements #
โ Only for native platforms (Android, iOS, macOS) โ Uses
SharedPreferences.
๐ Usage #
Define your message #
class MyMessage {
final String id;
final String payload;
MyMessage(this.id, this.payload);
Map<String, dynamic> toJson() => {'id': id, 'payload': payload};
static MyMessage fromJson(Map<String, dynamic> json) =>
MyMessage(json['id'], json['payload']);
}
UI Isolate (Main isolate) #
final queue = await PersistentQueue.getInstance<MyMessage>(
MyMessage.fromJson,
(msg) => msg.toJson(),
);
queue.bindUIIsolate();
queue.stream.listen((msg) async {
print("Received: \${msg.payload}");
await queue.ack(msg.id);
});
Background Isolate #
final queue = await PersistentQueue.getInstance<MyMessage>(
MyMessage.fromJson,
(msg) => msg.toJson(),
);
await queue.send(MyMessage('msg-id-001', 'Hello from background isolate!'));
๐งผ Clean Up #
await queue.clearAll();
๐ฆ Full Example #
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final queue = await PersistentQueue.getInstance<MyMessage>(
MyMessage.fromJson,
(msg) => msg.toJson(),
);
queue.bindUIIsolate();
queue.stream.listen((msg) async {
print("UI Isolate received: \${msg.payload}");
await queue.ack(msg.id);
});
Isolate.spawn(runBackgroundIsolate, null);
runApp(const MaterialApp(home: Scaffold(body: Center(child: Text('PersistentQueue Example')))));
}
void runBackgroundIsolate(_) async {
final queue = await PersistentQueue.getInstance<MyMessage>(
MyMessage.fromJson,
(msg) => msg.toJson(),
);
await queue.send(MyMessage('msg-id-\${DateTime.now().millisecondsSinceEpoch}', 'Hello from background isolate!'));
}
๐ Related #
๐ License #
MIT
๐ท TODO #
- โ Add support for desktop platforms via alternative storage
- โ Add tests for isolate communication reliability