spawn static method Null safety

Future<DriftIsolate> spawn(
  1. DatabaseOpener opener,
  2. {bool serialize = false}
)

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.

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 those setups, drift can serialize its internal communication channel to only send simple types across isolates. The serialize parameter, which is enabled by default, controls this behavior.

In most scenarios, serialize can be disabled for a considerable performance improvement.

Implementation

static Future<DriftIsolate> spawn(DatabaseOpener opener,
    {bool serialize = false}) async {
  final receiveServer = ReceivePort();
  final keyFuture = receiveServer.first;

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