DriftIsolate.inCurrent constructor

DriftIsolate.inCurrent(
  1. DatabaseOpener opener, {
  2. bool killIsolateWhenDone = false,
  3. bool serialize = false,
  4. bool shutdownAfterLastDisconnect = false,
  5. ReceivePort? port,
  6. void beforeShutdown()?,
})

Creates a DriftIsolate in the Isolate.current isolate. The returned DriftIsolate is an object than can be sent across isolates - any other isolate can then use DriftIsolate.connect to obtain a special database connection which operations are all executed on this isolate.

When killIsolateWhenDone is enabled (it defaults to false) and shutdownAll is called on the returned DriftIsolate, the isolate used to call DriftIsolate.inCurrent will be killed.

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

factory DriftIsolate.inCurrent(
  DatabaseOpener opener, {
  bool killIsolateWhenDone = false,
  bool serialize = false,
  bool shutdownAfterLastDisconnect = false,
  ReceivePort? port,
  void Function()? beforeShutdown,
}) {
  final server = RunningDriftServer(
    Isolate.current,
    opener(),
    killIsolateWhenDone: killIsolateWhenDone,
    port: port,
    beforeShutdown: beforeShutdown,
    shutDownAfterLastDisconnect: shutdownAfterLastDisconnect,
  );
  return DriftIsolate.fromConnectPort(
    server.portToOpenConnection,
    serialize: serialize,
  );
}