From 5dfbbe84bc9e59d79ce7ae761ce5d08bac8a21db Mon Sep 17 00:00:00 2001 From: lh900519 Date: Wed, 30 Aug 2023 18:56:47 +0800 Subject: [PATCH 1/2] fix: in the stream mode, request cannot be canceled --- dio/lib/src/adapters/io_adapter.dart | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/dio/lib/src/adapters/io_adapter.dart b/dio/lib/src/adapters/io_adapter.dart index 65e9ac6cf..8f9889b60 100644 --- a/dio/lib/src/adapters/io_adapter.dart +++ b/dio/lib/src/adapters/io_adapter.dart @@ -86,7 +86,10 @@ class IOHttpClientAdapter implements HttpClientAdapter { Stream? requestStream, Future? cancelFuture, ) async { - final httpClient = _configHttpClient(options.connectTimeout); + final httpClient = _configHttpClient( + options.connectTimeout, + newClient: options.responseType == ResponseType.stream, + ); final reqFuture = httpClient.openUrl(options.method, options.uri); late HttpClientRequest request; @@ -107,7 +110,17 @@ class IOHttpClientAdapter implements HttpClientAdapter { } if (cancelFuture != null) { - cancelFuture.whenComplete(() => request.abort()); + cancelFuture.whenComplete(() async { + // Abort request + request.abort(); + + if (options.responseType == ResponseType.stream) { + // Close the HttpClient, in the stream mode, there is a problem that cannot be canceled + httpClient.close(force: true); + // Reset HttpClient cache + _cachedHttpClient = null; + } + }); } // Set Headers @@ -227,7 +240,13 @@ class IOHttpClientAdapter implements HttpClientAdapter { ); } - HttpClient _configHttpClient(Duration? connectionTimeout) { + HttpClient _configHttpClient(Duration? connectionTimeout, + {bool newClient = false}) { + if (newClient) { + final client = _createHttpClient(); + return client..connectionTimeout = connectionTimeout; + } + return (_cachedHttpClient ??= _createHttpClient()) ..connectionTimeout = connectionTimeout; } From be0b55eb3748e64633caf0e99a3108ef5c967efc Mon Sep 17 00:00:00 2001 From: lh900519 Date: Mon, 4 Sep 2023 16:32:41 +0800 Subject: [PATCH 2/2] fix bug --- dio/lib/src/adapters/io_adapter.dart | 2 -- 1 file changed, 2 deletions(-) diff --git a/dio/lib/src/adapters/io_adapter.dart b/dio/lib/src/adapters/io_adapter.dart index 8f9889b60..b1043716a 100644 --- a/dio/lib/src/adapters/io_adapter.dart +++ b/dio/lib/src/adapters/io_adapter.dart @@ -117,8 +117,6 @@ class IOHttpClientAdapter implements HttpClientAdapter { if (options.responseType == ResponseType.stream) { // Close the HttpClient, in the stream mode, there is a problem that cannot be canceled httpClient.close(force: true); - // Reset HttpClient cache - _cachedHttpClient = null; } }); }