spawnSendPortHandshakeIsolate static method

Future<SendPort?> spawnSendPortHandshakeIsolate({
  1. required void entryPoint(
    1. List
    ),
  2. required List args,
  3. String? debugName,
})

spawn 一个 isolate,并通过握手拿到它的 SendPort

约定:entryPoint 的参数为 List,且最后一个元素为 main isolate 的 SendPort(握手端口)。

Implementation

static Future<SendPort?> spawnSendPortHandshakeIsolate({
  required void Function(List<dynamic>) entryPoint,
  required List<dynamic> args,
  String? debugName,
}) async {
  final ReceivePort rp = ReceivePort();
  try {
    await Isolate.spawn(
      entryPoint,
      <dynamic>[...args, rp.sendPort],
      debugName: debugName,
    );
    final dynamic first = await rp.first;
    return first is SendPort ? first : null;
  } catch (_) {
    return null;
  } finally {
    rp.close();
  }
}