diff --git a/dio/CHANGELOG.md b/dio/CHANGELOG.md index 46ed860db..306a2b79f 100644 --- a/dio/CHANGELOG.md +++ b/dio/CHANGELOG.md @@ -5,7 +5,7 @@ See the [Migration Guide][] for the complete breaking changes list.** ## Unreleased -*None.* +- Improve `SyncTransformer`'s stream transform. ## 5.3.4 diff --git a/dio/lib/src/transformers/sync_transformer.dart b/dio/lib/src/transformers/sync_transformer.dart index e2c6f336c..88827212d 100644 --- a/dio/lib/src/transformers/sync_transformer.dart +++ b/dio/lib/src/transformers/sync_transformer.dart @@ -62,9 +62,8 @@ class SyncTransformer extends Transformer { return responseBody; } - final showDownloadProgress = options.onReceiveProgress != null; final int totalLength; - if (showDownloadProgress) { + if (options.onReceiveProgress != null) { totalLength = int.parse( responseBody.headers[Headers.contentLengthHeader]?.first ?? '-1', ); @@ -72,27 +71,15 @@ class SyncTransformer extends Transformer { totalLength = 0; } - int received = 0; - final stream = responseBody.stream.transform( - StreamTransformer.fromHandlers( - handleData: (data, sink) { - sink.add(data); - if (showDownloadProgress) { - received += data.length; - options.onReceiveProgress?.call(received, totalLength); - } - }, - ), - ); - final streamCompleter = Completer(); int finalLength = 0; // Keep references to the data chunks and concatenate them later. final chunks = []; - final subscription = stream.listen( - (chunk) { + final subscription = responseBody.stream.listen( + (Uint8List chunk) { finalLength += chunk.length; chunks.add(chunk); + options.onReceiveProgress?.call(finalLength, totalLength); }, onError: (Object error, StackTrace stackTrace) { streamCompleter.completeError(error, stackTrace);