NetworkInputStream constructor

NetworkInputStream(
  1. Stream<List<int>> _sourceStream
)

An InputStream implementation that reads bytes from a Dart Stream<List<int>>.

This is typically used to wrap network response streams such as HttpClientResponse in Dart.

The class buffers incoming chunks and provides methods to read the stream byte-by-byte in a non-blocking manner.

Example usage:

final response = await HttpClient().getUrl(Uri.parse('https://example.com'));
final inputStream = NetworkInputStream(response);

int byte;
while ((byte = await inputStream.readByte()) != -1) {
  print(byte);
}
await inputStream.close();

The provided _sourceStream must emit List<int> values (byte chunks).

Implementation

NetworkInputStream(this._sourceStream) {
  _subscription = _sourceStream.listen(
    (data) {
      _buffer = Uint8List.fromList([..._buffer.sublist(_bufferOffset), ...data]);
      _bufferOffset = 0;
      _readCompleter?.complete();
      _readCompleter = null;
    },
    onError: (error) {
      _readCompleter?.completeError(IOException('Error reading from network stream: $error', cause: error));
      _readCompleter = null;
      _isDone = true;
      close(); // Close on error
    },
    onDone: () {
      _isDone = true;
      _readCompleter?.complete();
      _readCompleter = null;
    },
    cancelOnError: true,
  );
}