cancel method

void cancel([
  1. String? reason
])

Cancels the request.

取消请求。

Parameters / 参数:

  • reason: Optional reason for cancellation / 取消原因(可选)

If the request is already cancelled, this method does nothing. All registered callbacks will be notified when the request is cancelled.

如果请求已经被取消,此方法不执行任何操作。 当请求被取消时,所有注册的回调都会被通知。

Example / 示例:

cancelToken.cancel("User cancelled the operation");

Implementation

void cancel([String? reason]) {
  if (_isCancelled) {
    return; // Already cancelled / 已经取消,不重复执行
  }

  _isCancelled = true;
  _cancelReason = reason ?? 'Request cancelled';

  // Notify all callbacks / 通知所有回调
  for (final callback in _callbacks) {
    try {
      callback(_cancelReason);
    } catch (e) {
      // Ignore errors in callbacks / 忽略回调中的错误
    }
  }

  // Clear callback list / 清空回调列表
  _callbacks.clear();
}