reduce<Item> method

Future<Item> reduce<Item>(
  1. Iterable<Item> items,
  2. Future<Item> combine(
    1. Item a,
    2. Item b
    ), {
  3. int priority = 0,
  4. Duration? timeout,
  5. RetryPolicy? retry,
  6. TaskTimeouts? timeouts,
})

Reduces items to a single value using combine function.

Items are processed in order, but the reduction happens sequentially after all items are processed.

Example:

final limit = fLimit(2);
final items = [1, 2, 3, 4, 5];

final sum = await limit.reduce(items, (a, b) async => a + b);
// sum = 15

Implementation

Future<Item> reduce<Item>(
  Iterable<Item> items,
  Future<Item> Function(Item a, Item b) combine, {
  int priority = 0,
  Duration? timeout,
  RetryPolicy? retry,
  TaskTimeouts? timeouts,
}) async {
  final itemList = items.toList();
  if (itemList.isEmpty) {
    throw StateError('No element');
  }

  var accumulator = itemList.first;
  for (var i = 1; i < itemList.length; i++) {
    accumulator = await this(
      () => combine(accumulator, itemList[i]),
      priority: priority,
      timeout: timeout,
      retry: retry,
      timeouts: timeouts,
    ).future;
  }
  return accumulator;
}