compute<R, T> static method

Future<R> compute<R, T>(
  1. WorkerEntrypoint<T> entrypoint,
  2. T payload, {
  3. String name = "",
})

Spin up a short lived worker, execute the entrypoint and get the result

Implementation

static Future<R> compute<R, T>(
  WorkerEntrypoint<T> entrypoint,
  T payload, {
  String name = "",
}) async {
  final onError = ReceivePort();
  final worker = EasyWorker(
    Entrypoint(entrypoint),
    workerName: "compute${name.trim().isEmpty ? "" : ":$name"}",
    initialMessage: payload,
    onError: onError.sendPort,
    // onError: onError.sendPort,
  );
  final Completer<R> completer = Completer<R>();
  try {
    worker.stream.take(1).listen((event) => completer.complete(event));
    onError.take(1).listen((event) => completer.completeError(event));

    final result = await completer.future;

    return result;
  } catch (e) {
    rethrow;
  } finally {
    onError.close();
    worker.dispose();
  }
}