spawn static method

Future<DriftIsolate> spawn(
  1. DatabaseOpener opener, {
  2. bool serialize = false,
  3. Future<Isolate> isolateSpawn<T>(
    1. void (
      1. T
      ),
    2. T
    ) = Isolate.spawn,
})

Creates a new DriftIsolate on a background thread.

The opener function will be used to open the DatabaseConnection used by the isolate.

Because opener will be called on another isolate with its own memory, it must either be a top-level member or a static class method.

To close the isolate later, use shutdownAll. Or, if you know that only a single client will connect, set singleClientMode: true in connect. That way, the drift isolate will shutdown when the client is closed.

The optional isolateSpawn parameter can be used to make drift use something else instead of Isolate.spawn to spawn the isolate. This may be useful if you want to set additional options on the isolate or otherwise need a reference to it.

Internally, drift uses ports from dart:isolate to send commands to an internal server dispatching database actions. In most setups, those ports can send and receive almost any Dart object. In special cases though, the platform only supports sending simple types across send types. In particular, isolates across different Flutter engines (such as the ones spawned by the workmanager package) are unable to handle most objects. To support these setups, drift can serialize the objects sent to the background isolates into simple lists. This is adds considerable overhead, but is necessary to make two independent isolates talk to each other.

The serialize parameter can be used to explicitly enable or disable this behavior. By default, drift will attempt to send a test message to infer whether serialization is necessary or not.

Implementation

static Future<DriftIsolate> spawn(
  DatabaseOpener opener, {
  bool serialize = false,
  Future<Isolate> Function<T>(void Function(T), T) isolateSpawn =
      Isolate.spawn,
}) async {
  final receiveServer = ReceivePort('drift isolate connect');
  final keyFuture = receiveServer.first;

  await isolateSpawn(_startDriftIsolate, [receiveServer.sendPort, opener]);
  final key = await keyFuture as SendPort;
  return DriftIsolate.fromConnectPort(key, serialize: serialize);
}