reduce<Item> method
Future<Item>
reduce<Item>(
- Iterable<
Item> items, - Future<
Item> combine(- Item a,
- Item b
- int priority = 0,
- Duration? timeout,
- RetryPolicy? retry,
- 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;
}