bufferCount method
Buffers incoming events into lists of size count.
When the buffer reaches count elements, it is emitted. Any remaining
events are emitted when the stream closes.
Example:
myStream.buffer(3).listen((chunk) {
print('Received a chunk of ${chunk.length} items');
});
Implementation
Stream<List<T>> bufferCount(int count) {
if (count <= 0) {
throw ArgumentError('Buffer count must be greater than zero');
}
final bucket = <T>[];
return transform(
StreamTransformer<T, List<T>>.fromHandlers(
handleData: (data, sink) {
bucket.add(data);
if (bucket.length >= count) {
sink.add(List<T>.from(bucket));
bucket.clear();
}
},
handleDone: (sink) {
if (bucket.isNotEmpty) sink.add(List<T>.from(bucket));
sink.close();
},
),
);
}