From 32ad527340875b616f3a5858b292ba8ec5f9e4fc Mon Sep 17 00:00:00 2001 From: Steve Browne Date: Tue, 3 May 2022 17:10:36 -0400 Subject: [PATCH] Made some minor changes to better handle when a streaming request is aborted so that we stop reading gracefully. --- lib/src/client/transport/fetch_transport.dart | 21 ++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/lib/src/client/transport/fetch_transport.dart b/lib/src/client/transport/fetch_transport.dart index 0c03f80e..bfad8051 100644 --- a/lib/src/client/transport/fetch_transport.dart +++ b/lib/src/client/transport/fetch_transport.dart @@ -104,7 +104,8 @@ class FetchHttpRequest { Stream get onError => onErrorController.stream; // Response information - CancelableOperation? _cancelable; + CancelableOperation? _cancelableFetch; + CancelableOperation? _cancelableSend; dynamic _response; dynamic get response => _response; int get status => @@ -125,6 +126,12 @@ class FetchHttpRequest { List.from(js_util.callMethod(obj, 'keys', [])); Future send([List? data]) async { + final doSend = _doSend(data); + _cancelableSend = CancelableOperation.fromFuture(doSend); + await doSend; + } + + Future _doSend([List? data]) async { final wgs = WorkerGlobalScope.instance; _setReadyState(HttpRequest.LOADING); @@ -139,11 +146,15 @@ class FetchHttpRequest { referrerPolicy: referrerPolicy, body: data, headers: js_util.jsify(headers)); - final operation = _cancelable = CancelableOperation.fromFuture( + final operation = _cancelableFetch = CancelableOperation.fromFuture( js_util.promiseToFuture(js_util.callMethod(wgs, 'fetch', [uri, init]))); _response = await operation.value; _setReadyState(HttpRequest.HEADERS_RECEIVED); + if (_cancelableSend?.isCanceled ?? false) { + return; + } + if (status < 200 || status >= 300) { onErrorController.add(status); } @@ -156,6 +167,9 @@ class FetchHttpRequest { while (true) { final result = await js_util.promiseToFuture(reader.read()); + if (_cancelableSend?.isCanceled ?? false) { + return; + } final value = js_util.getProperty(result, 'value'); if (value != null) { onProgressController.add(value as Uint8List); @@ -180,7 +194,8 @@ class FetchHttpRequest { } void abort() async { - await _cancelable?.cancel(); + await _cancelableFetch?.cancel(); + await _cancelableSend?.cancel(); close(); }