createIsolate static method

Create Isolate, initialize messages and run your function with IsolateMessenger and user's IsolateInitializer func

Implementation

static Future<IsolateManagerImpl> createIsolate(
  IsolateRun run,
  IsolateInitializer initializer,
  IsolateInitializeArguments args,
) async {
  assert(
    '$initializer'.contains(' static'),
    'Initialize function must be a static or global function',
  );

  final fromIsolate = ReceivePort();
  final toIsolateCompleter = Completer<SendPort>();
  final isolate = await Isolate.spawn<_IsolateSetup>(
    _runInIsolate,
    _IsolateSetup(
      fromIsolate.sendPort,
      run,
      initializer,
      args
    ),
    errorsAreFatal: false,
  );

  final fromIsolateStream = fromIsolate.asBroadcastStream();
  final subscription = fromIsolateStream.listen((message) {
    if (message is SendPort) {
      toIsolateCompleter.complete(message);
    }
  });
  final toIsolate = await toIsolateCompleter.future;
  await subscription.cancel();

  final isolateMessenger = IsolateMessenger(
    fromIsolateStream.where((event) => event is Event)
        .cast<Event>(),
    toIsolate.send
  );

  return IsolateManagerImpl(
    IsolateWrapperImpl(isolate),
    isolateMessenger,
  );
}