multiPartProgress method

Stream<double> multiPartProgress({
  1. required StreamedResponse response,
})

multiPartProgress Returns a stream of the multipart progress for the given HTTP response.

The stream will emit doubles representing the percentage of bytes received.

Example usage:

RhUtils.instance.multiPartProgress(response: response).listen((event) {
  // Functions using [event]
});

Implementation

Stream<double> multiPartProgress({required http.StreamedResponse response}) {
  final controller = StreamController<double>();
  final totalBytes = response.contentLength ?? -1;
  var receivedBytes = 0;

  response.stream.listen(
    (List<int> chunk) {
      receivedBytes += chunk.length;
      if (totalBytes >= 0) {
        final percentage = (receivedBytes / totalBytes) * 100;
        controller.add(percentage);
      }
    },
    onDone: () {
      controller.close();
    },
    onError: (error) {
      controller.addError(error);
    },
    cancelOnError: true,
  );

  return controller.stream;
}