Skip to content

Commit

Permalink
Fix 'Future already completed' error when connectTimeout was set (cfu…
Browse files Browse the repository at this point in the history
  • Loading branch information
davidmigloz committed Dec 14, 2022
1 parent 9040bde commit 4f73122
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 7 deletions.
27 changes: 21 additions & 6 deletions dio/lib/src/adapters/browser_adapter.dart
Original file line number Diff line number Diff line change
Expand Up @@ -61,12 +61,13 @@ class BrowserHttpClientAdapter implements HttpClientAdapter {
);
});

bool haveSent = false;
Timer? connectTimeoutTimer;

if (options.connectTimeout > 0) {
Future.delayed(Duration(milliseconds: options.connectTimeout)).then(
(value) {
if (!haveSent) {
connectTimeoutTimer = Timer(
Duration(milliseconds: options.connectTimeout),
() {
if (!completer.isCompleted) {
completer.completeError(
DioError(
requestOptions: options,
Expand All @@ -76,19 +77,26 @@ class BrowserHttpClientAdapter implements HttpClientAdapter {
StackTrace.current,
);
xhr.abort();
} else {
// connectTimeout is triggered after the fetch has been completed.
}
},
);
}

int sendStart = 0;
xhr.upload.onProgress.listen((event) {
haveSent = true;
// This event will only be triggered if a request body exists.
if (connectTimeoutTimer != null) {
connectTimeoutTimer!.cancel();
connectTimeoutTimer = null;
}

if (options.sendTimeout > 0) {
if (sendStart == 0) {
sendStart = DateTime.now().millisecondsSinceEpoch;
}
var t = DateTime.now().millisecondsSinceEpoch;
final t = DateTime.now().millisecondsSinceEpoch;
if (t - sendStart > options.sendTimeout) {
completer.completeError(
DioError(
Expand All @@ -110,6 +118,11 @@ class BrowserHttpClientAdapter implements HttpClientAdapter {

int receiveStart = 0;
xhr.onProgress.listen((event) {
if (connectTimeoutTimer != null) {
connectTimeoutTimer!.cancel();
connectTimeoutTimer = null;
}

if (options.receiveTimeout > 0) {
if (receiveStart == 0) {
receiveStart = DateTime.now().millisecondsSinceEpoch;
Expand All @@ -135,6 +148,7 @@ class BrowserHttpClientAdapter implements HttpClientAdapter {
});

xhr.onError.first.then((_) {
connectTimeoutTimer?.cancel();
// Unfortunately, the underlying XMLHttpRequest API doesn't expose any
// specific information about the error itself.
completer.completeError(
Expand All @@ -149,6 +163,7 @@ class BrowserHttpClientAdapter implements HttpClientAdapter {

cancelFuture?.then((err) {
if (xhr.readyState < 4 && xhr.readyState > 0) {
connectTimeoutTimer?.cancel();
try {
xhr.abort();
} catch (e) {
Expand Down
4 changes: 3 additions & 1 deletion example_flutter_app/lib/http.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import 'package:dio/dio.dart';

var dio = Dio();
var dio = Dio(BaseOptions(
connectTimeout: 3000,
));

0 comments on commit 4f73122

Please sign in to comment.