readChunkedStream<T> function

Future<List<T>> readChunkedStream<T>(
  1. Stream<List<T>> input, {
  2. int? maxSize,
})

Read all chunks from input and return a list consisting of items from all chunks.

If the maximum number of items exceeded maxSize this will stop reading and throw MaximumSizeExceeded.

Example

import 'dart:io';

List<int> readFile(String filePath) async {
  Stream<List<int>> fileStream = File(filePath).openRead();
  List<int> contents = await readChunkedStream(fileStream);
  return contents;
}

If reading a byte stream of type Stream<List<int>> consider using readByteStream instead.

Implementation

Future<List<T>> readChunkedStream<T>(
  Stream<List<T>> input, {
  int? maxSize,
}) async {
  if (maxSize != null && maxSize < 0) {
    throw ArgumentError.value(maxSize, 'maxSize must be positive, if given');
  }

  final result = <T>[];
  await for (final chunk in input) {
    result.addAll(chunk);
    if (maxSize != null && result.length > maxSize) {
      throw MaximumSizeExceeded(maxSize);
    }
  }
  return result;
}