Line data Source code
1 : import 'dart:async'; 2 : import 'dio_error.dart'; 3 : import 'options.dart'; 4 : 5 : /// You can cancel a request by using a cancel token. 6 : /// One token can be shared with different requests. 7 : /// when a token's [cancel] method invoked, all requests 8 : /// with this token will be cancelled. 9 : class CancelToken { 10 2 : CancelToken() { 11 4 : _completer = Completer<DioError>(); 12 : } 13 : 14 : /// Whether is throw by [cancel] 15 1 : static bool isCancel(DioError e) { 16 2 : return e.type == DioErrorType.cancel; 17 : } 18 : 19 : /// If request have been canceled, save the cancel Error. 20 : DioError? _cancelError; 21 : 22 : /// If request have been canceled, save the cancel Error. 23 2 : DioError? get cancelError => _cancelError; 24 : 25 : late Completer<DioError> _completer; 26 : 27 : RequestOptions? requestOptions; 28 : 29 : /// whether cancelled 30 0 : bool get isCancelled => _cancelError != null; 31 : 32 : /// When cancelled, this future will be resolved. 33 6 : Future<DioError> get whenCancel => _completer.future; 34 : 35 : /// Cancel the request 36 2 : void cancel([dynamic reason]) { 37 4 : _cancelError = DioError( 38 : type: DioErrorType.cancel, 39 : error: reason, 40 2 : requestOptions: requestOptions ?? RequestOptions(path: ''), 41 : ); 42 6 : _cancelError!.stackTrace = StackTrace.current; 43 : 44 4 : if (!_completer.isCompleted) { 45 6 : _completer.complete(_cancelError); 46 : } 47 : } 48 : }