Skip to content

Commit 32ad527

Browse files
author
Steve Browne
committed
Made some minor changes to better handle when a streaming request is aborted so that we stop reading gracefully.
1 parent e627db5 commit 32ad527

File tree

1 file changed

+18
-3
lines changed

1 file changed

+18
-3
lines changed

lib/src/client/transport/fetch_transport.dart

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,8 @@ class FetchHttpRequest {
104104
Stream<int> get onError => onErrorController.stream;
105105

106106
// Response information
107-
CancelableOperation<dynamic>? _cancelable;
107+
CancelableOperation<dynamic>? _cancelableFetch;
108+
CancelableOperation<dynamic>? _cancelableSend;
108109
dynamic _response;
109110
dynamic get response => _response;
110111
int get status =>
@@ -125,6 +126,12 @@ class FetchHttpRequest {
125126
List<String>.from(js_util.callMethod(obj, 'keys', []));
126127

127128
Future send([List<int>? data]) async {
129+
final doSend = _doSend(data);
130+
_cancelableSend = CancelableOperation.fromFuture(doSend);
131+
await doSend;
132+
}
133+
134+
Future _doSend([List<int>? data]) async {
128135
final wgs = WorkerGlobalScope.instance;
129136
_setReadyState(HttpRequest.LOADING);
130137

@@ -139,11 +146,15 @@ class FetchHttpRequest {
139146
referrerPolicy: referrerPolicy,
140147
body: data,
141148
headers: js_util.jsify(headers));
142-
final operation = _cancelable = CancelableOperation.fromFuture(
149+
final operation = _cancelableFetch = CancelableOperation.fromFuture(
143150
js_util.promiseToFuture(js_util.callMethod(wgs, 'fetch', [uri, init])));
144151

145152
_response = await operation.value;
146153
_setReadyState(HttpRequest.HEADERS_RECEIVED);
154+
if (_cancelableSend?.isCanceled ?? false) {
155+
return;
156+
}
157+
147158
if (status < 200 || status >= 300) {
148159
onErrorController.add(status);
149160
}
@@ -156,6 +167,9 @@ class FetchHttpRequest {
156167

157168
while (true) {
158169
final result = await js_util.promiseToFuture(reader.read());
170+
if (_cancelableSend?.isCanceled ?? false) {
171+
return;
172+
}
159173
final value = js_util.getProperty(result, 'value');
160174
if (value != null) {
161175
onProgressController.add(value as Uint8List);
@@ -180,7 +194,8 @@ class FetchHttpRequest {
180194
}
181195

182196
void abort() async {
183-
await _cancelable?.cancel();
197+
await _cancelableFetch?.cancel();
198+
await _cancelableSend?.cancel();
184199
close();
185200
}
186201

0 commit comments

Comments
 (0)