foreach<T> static method

FutureOr<void> foreach<T>(
  1. List<T> values,
  2. FutureOr<void> handler(
    1. T item
    )
)

Executes a 'for in' loop function in a different thread.

The foreach method works like a traditional 'for in' loop, iterating through the values, running the handler function on each value provided in the parameters.

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 {
  await Parallel.foreach(['test'], writeFile);
}

// Top-level function (or static)
void writeFile(String name) {
  File(Directory.systemTemp.path + '/$name').createSync();
}

Implementation

static FutureOr<void> foreach<T>(
    List<T> values, FutureOr<void> 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(null);
        worker.dispose();
      },
      _isolateHandler,
      initialMessage: _ParallelForeachParams(item, handler),
    );
  }

  await Future.wait(completerList.values.map((e) => e.future));
}