From 572efd31ff29a163525d0de4bd8c4ac133b2ee8e Mon Sep 17 00:00:00 2001 From: Simon Binder Date: Sat, 25 Apr 2020 17:48:28 +0200 Subject: [PATCH] Document how to safely share MoorIsolates --- .../en/docs/Advanced Features/isolates.md | 22 +++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/docs/content/en/docs/Advanced Features/isolates.md b/docs/content/en/docs/Advanced Features/isolates.md index b3026172..9c08acf2 100644 --- a/docs/content/en/docs/Advanced Features/isolates.md +++ b/docs/content/en/docs/Advanced Features/isolates.md @@ -123,8 +123,7 @@ It will disconnect all databases and then close the background isolate, releasin ## Common operation modes -The `MoorIsolate` object itself can be sent across isolates, so if you have more than one isolate -from which you want to use moor, that's no problem! +You can use a `MoorIsolate` across multiple isolates you control and connect from any of them. __One executor isolate, one foreground isolate__: This is the most common usage mode. You would call `MoorIsolate.spawn` from the `main` method in your Flutter or Dart app. Similar to the example above, @@ -144,6 +143,25 @@ above. The background isolate would _also_ call `MoorIsolate.connect` and create of the generated database class. Writes to one database will be visible to the other isolate and also update query streams. +To safely send a `MoorIsolate` instance across a `SendPort`, it's recommended to instead send the +underlying `SendPort` used internally by `MoorIsolate`: + +```dart +// Don't do this, it doesn't work in all circumstances +void shareMoorIsolate(MoorIsolate isolate, SendPort sendPort) { + sendPort.send(isolate); +} + +// Instead, send the underlying SendPort: +void shareMoorIsolate(MoorIsolate isolate, SendPort sendPort) { + sendPort.send(isolate.connectPort); +} +``` + +The receiving end can reconstruct a `MoorIsolate` from a `SendPort` by using the +`MoorIsolate.fromConnectPort` constructor. That `MoorIsolate` behaves exactly like the original +one, but we only had to send a primitive `SendPort` and not a complex Dart object. + ## How does this work? Are there any limitations? All moor features are supported on background isolates and work out of the box. This includes