mapBatched<A, T> function

Future<List<T>> mapBatched<A, T>(
  1. Iterable<A> items,
  2. AsyncMapper<A, T> fn, {
  3. int batchSize = 5,
})

Batch async (e.g. 5 at a time). Roadmap #182. Audited: 2026-06-12 11:26 EDT

Implementation

Future<List<T>> mapBatched<A, T>(
  Iterable<A> items,
  AsyncMapper<A, T> fn, {
  int batchSize = 5,
}) async {
  // A non-positive batch size would make `i += batchSize` never advance (or go
  // backward) and hang forever; treat anything below 1 as a batch of 1.
  final int size = batchSize < 1 ? 1 : batchSize;
  final List<A> list = items.toList();
  // A collection-for builds the result in one pass (O(n)) and replaces the
  // addAll accumulator. Elements are evaluated in order, so each batch is still
  // awaited before the next batch starts.
  return <T>[
    for (int i = 0; i < list.length; i += size)
      ...await Future.wait(list.skip(i).take(size).map(fn), eagerError: false),
  ];
}