spawnedMain function

Future<void> spawnedMain(
  1. List<String> args,
  2. SendPort parentPort,
  3. int id,
  4. Function run, [
  5. FutureOr<bool> stop()?,
])

Helper to executed a spawned Dart script by DartSpawner.

Implementation

Future<void> spawnedMain(
    List<String> args, SendPort parentPort, int id, Function run,
    [FutureOr<bool> Function()? stop]) async {
  final messagePort = ReceivePort();

  var debugName = Isolate.current.debugName;

  var isolateId = debugName != null ? 'Isolate#$id($debugName)' : 'Isolate#$id';

  messagePort.listen((msg) {
    if (msg['cmd'] == 'stop') {
      _stopSpawned(isolateId, messagePort, stop, parentPort);
    }
  });

  print('[$isolateId] Running: $run');

  FutureOr ret;

  if (run is Function()) {
    ret = run();
  } else if (run is Function(List<String> a)) {
    ret = run(args);
  }

  print('[$isolateId] Return: $ret');

  parentPort.send({'status': 'ok', 'port': messagePort.sendPort});

  if (ret is Future) {
    print('[$isolateId] Waiting return: $ret');
    await ret;
  }

  _stopSpawned(isolateId, messagePort, stop, parentPort);
}