waitConcurrency method
Executes the functions in this iterable, running at most concurrency futures simultaneously.
This is useful for batch processing (e.g., uploading files) without overwhelming resources.
concurrency must be positive.
Results are returned in completion order, not input order.
If any task throws, the returned future completes with that error. Any in-flight tasks continue running and their errors are handled internally to avoid unhandled exceptions.
Example:
await tasks.waitConcurrency(concurrency: 5);
Implementation
Future<List<T>> waitConcurrency({int concurrency = 5}) async {
if (concurrency <= 0) throw ArgumentError('Concurrency must be positive');
final results = <T>[];
final active = <Future<void>>{};
try {
for (final task in this) {
while (active.length >= concurrency) {
await Future.any(active);
}
late Future<void> future;
future = task().then((r) {
results.add(r);
}).whenComplete(() {
active.remove(future);
});
active.add(future);
}
await Future.wait(active);
} catch (_) {
for (final task in active) {
// ignore: unawaited_futures
task.catchError((_) {});
}
rethrow;
}
return results;
}