consolidateStreamedResponseBytes function
Future<Uint8List>
consolidateStreamedResponseBytes(
- StreamedResponse response, {
- BytesReceivedCallback? onBytesReceived,
Efficiently converts the response body of an StreamedResponse
into a
Uint8List.
The future returned will forward any error emitted by response
.
The onBytesReceived
callback, if specified, will be invoked for every
chunk of bytes that is received while consolidating the response bytes.
If the callback throws an error, processing of the response will halt, and
the returned future will complete with the error that was thrown by the
callback. For more information on how to interpret the parameters to the
callback, see the documentation on BytesReceivedCallback.
Implementation
Future<Uint8List> consolidateStreamedResponseBytes(
StreamedResponse response, {
BytesReceivedCallback? onBytesReceived,
}) {
final Completer<Uint8List> completer = Completer<Uint8List>.sync();
final _OutputBuffer output = _OutputBuffer();
ByteConversionSink sink = output;
int? expectedContentLength = response.contentLength;
if (expectedContentLength == -1) {
expectedContentLength = null;
}
int bytesReceived = 0;
late final StreamSubscription<List<int>> subscription;
subscription = response.stream.listen((List<int> chunk) {
sink.add(chunk);
if (onBytesReceived != null) {
bytesReceived += chunk.length;
try {
onBytesReceived(bytesReceived, expectedContentLength);
} catch (error, stackTrace) {
completer.completeError(error, stackTrace);
subscription.cancel();
return;
}
}
}, onDone: () {
sink.close();
completer.complete(output.bytes);
}, onError: completer.completeError, cancelOnError: true);
return completer.future;
}