๐Ÿ“จ Cross Isolate Messenger

januscaler

pub package

All Contributors

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!'));
}


๐Ÿ“„ License

MIT

๐Ÿ‘ท TODO

  • Add support for desktop platforms via alternative storage
  • Add tests for isolate communication reliability