create<InitParams> static method

Future<IsolateClient> create<InitParams>(
  1. InitClient<InitParams> initClient, {
  2. required InitParams params,
  3. void messageHandler(
    1. Object?
    )?,
  4. SendPort? onError,
  5. SendPort? onExit,
  6. bool errorsAreFatal = false,
})

Create a new IsolateClient. The IsolateClient will spawn a new Isolate, and create a standard Client on this Isolate given the passed InitClient function. initClient must a static or top-level function in order to be send over the isolate. if the initClient function needs params (e.g. a path for the HiveBox, since you cannot call path_provider on to other isolate without jumping through hoops), you can pass these params here. Note that params must only contain types that can be sent over Isolates. This essentials means, only data that you could also serialize to JSON. Note: isolates are not supported on the web. On the web, please use the standard Client.

The onError, onExit and errorsAreFatal parameters are forwarded to the Isolate.spawn method.

Implementation

static Future<IsolateClient> create<InitParams>(
  InitClient<InitParams> initClient, {
  required InitParams params,
  void Function(Object?)? messageHandler,
  SendPort? onError,
  SendPort? onExit,
  bool errorsAreFatal = false,
}) async {
  final client = IsolateClient._();

  client._globalReceivePort =
      ReceivePort('package:ferry/ferry_isolate.dart:main');

  // setup custom messages from isolate -> main if necessary
  if (messageHandler != null) {
    client._messageHandlerReceivePort =
        ReceivePort('package:ferry/ferry_isolate.dart:messageHandler');
    client._messageHandlerReceivePort!.listen(messageHandler);
  } else {
    client._messageHandlerReceivePort = null;
  }

  final completer = Completer();

  // the first message
  unawaited(client._globalReceivePort.first.then((value) {
    assert(value is SendPort,
        'internal error: the first message sent must be the SendPort');
    client._commandSendPort = value;
    completer.complete();
  }));

  unawaited(Isolate.spawn<_IsolateInit<InitParams>>(
    _isolateClientEntryPoint,
    _IsolateInit<InitParams>(
      initClient,
      client._globalReceivePort.sendPort,
      client._messageHandlerReceivePort?.sendPort,
      params,
    ),
    errorsAreFatal: errorsAreFatal,
    onError: onError,
    onExit: onExit,
  ));

  await completer.future;

  return client;
}