map<T, R> static method

FutureOr<List<R>> map<T, R>(
  1. List<T> values,
  2. FutureOr<R> handler(
    1. T item
    )
)

Executes a map function in a different thread.

The map method works like a traditional mapper, iterating through the values, adapting using the handler function provided in the parameters, and returning a new List with the adapted values.

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 values should use primitive values.

Example:


Future main() async {
  final result = await Parallel.map([1, 2, 3, 4], intToStringAdapter);
  print(result); // Should print all the values as a String
}

// Top-level function (or static)
String intToStringAdapter(int i) {
  return i.toString();
}

Implementation

static FutureOr<List<R>> map<T, R>(
    List<T> values, FutureOr<R> Function(T item) handler) async {
  final completerList =
      Map.fromIterables(values, values.map((e) => Completer()));

  for (final item in values) {
    final worker = Worker();
    await worker.init(
      (data, _) {
        completerList[item]?.complete(data);
        worker.dispose();
      },
      _isolateHandler,
      initialMessage: _ParallelMapParams(item, handler),
    );
  }

  final result = await Future.wait(completerList.values.map((e) => e.future));
  return result.cast<R>();
}