foreachService<T> static method

Future<void> foreachService<T>(
  1. Iterable<T> services,
  2. CancellationToken token,
  3. bool concurrent,
  4. bool abortOnFirstException,
  5. List<Exception> exceptions,
  6. Future<void> operation(
    1. T value,
    2. CancellationToken token
    ),
)

Implementation

static Future<void> foreachService<T>(
  Iterable<T> services,
  CancellationToken token,
  bool concurrent,
  bool abortOnFirstException,
  List<Exception> exceptions,
  Future<void> Function(T value, CancellationToken token) operation,
) async {
  if (concurrent) {
    var futures = <Future<void>>[];

    for (var service in services) {
      var completer = Completer<void>();

      try {
        completer.complete(operation(service, token));
      } on Exception catch (ex) {
        exceptions.add(ex);
        continue;
      }

      if (completer.isCompleted) {
      } else {
        futures.add(completer.future);
      }
    }

    if (futures.isNotEmpty) {
      Future<void> groupedFutures = Future.wait(futures);

      try {
        await groupedFutures;
      } on Exception catch (ex) {
        exceptions.add(ex);
      }
    }
  } else {
    for (var service in services) {
      try {
        await operation(service, token);
      } on Exception catch (ex) {
        exceptions.add(ex);
        if (abortOnFirstException) {
          return;
        }
      }
    }
  }
}