cancelOn method

Future<T> cancelOn(
  1. CancellationToken? cancellationToken
)

Returns a Future that either returns the result or error of this Future or contains an Exception when the CancellationToken is notified before this Future has completed.

The Exception that is thrown on cancellation is either the Exception given to the CancellationToken in the default constructor or CanceledException when no custom Exception is defined for the CancellationToken. When null is passed as CancellationToken, this Future is returned as-is.

Implementation

Future<T> cancelOn(CancellationToken? cancellationToken) {
  if (cancellationToken == null) {
    return this;
  }

  final comp = Completer<T>();
  final key = cancellationToken.attach(([e]) {
    if (!comp.isCompleted) {
      comp.completeError(e ?? CanceledException());
    }
  });

  then((value) {
    cancellationToken.detach(key);
    if (!comp.isCompleted) {
      comp.complete(value);
    }
  }).catchError((value) {
    cancellationToken.detach(key);
    if (!comp.isCompleted) {
      comp.completeError(value);
    }
  });

  return comp.future;
}