countStream<R> function

Future<int> countStream<R>(
  1. Stream<R> stream, {
  2. required int count(
    1. R response
    ),
  3. int maxPages = 20,
})

Counts items from a paginated server stream with a maximum page cap. Only accumulates the count, not the items themselves.

Implementation

Future<int> countStream<R>(
  Stream<R> stream, {
  required int Function(R response) count,
  int maxPages = 20,
}) async {
  var total = 0;
  var pages = 0;
  await for (final response in stream) {
    final c = count(response);
    total += c;
    if (++pages >= maxPages || c == 0) break;
  }
  return total;
}