上一篇讲了 Dio 的 CancelToken 的使用,本篇来从源码解析 CancelToken 是如何实现取消网络请求的。相关的内容如下:
- CancelToken 类的实现
- CancelToken 如何取消网络请求
CancelToken 类
CalcelToken类的代码并不多,我们直接复制下来一个个过一遍。
import 'dart:async';
import 'dio_error.dart';
import 'options.dart';
/// You can cancel a request by using a cancel token.
/// One token can be shared with different requests.
/// when a token's [cancel] method invoked, all requests
/// with this token will be cancelled.
class CancelToken {
CancelToken() {
_completer = Completer<DioError>();
}
/// Whether is throw by [cancel]
static bool isCancel(DioError e) {
return e.type == DioErrorType.cancel;
}
/// If request have been canceled, save the cancel Error.
DioError? _cancelError;
/// If request have been canceled, save the cancel Error.
DioError? get cancelError =&