run<T, R> static method

FutureOr<R?> run<T, R>(
  1. ParallelCallback<T, R> handler, {
  2. T? entryValue,
})

Executes a function in a different thread.

The run method will run the handler function provided in a separated thread, returning a value or not. There is also an entryValue parameter that can be used inside the handler.

Important note: Isolates/Threads don't share memory between them, which means that the handler provided should be a top-level or static function and the entryValue should use primitive values.

Example:


Future main() async {
  final result = await Parallel.run(isEven, entryValue: 1);
  print(result);
}

// Top-level function (or static)
bool isEven({int? item}) {
  return item != null && item % 2 == 0;
}

Implementation

static FutureOr<R?> run<T, R>(ParallelCallback<T, R> handler,
    {T? entryValue}) async {
  final completer = Completer();
  final worker = Worker();
  await worker.init(
    (data, _) {
      completer.complete(data);
      worker.dispose();
    },
    _isolateHandler,
    initialMessage: _ParallelRunParams<T, R>(entryValue, handler),
  );
  return await completer.future;
}