Cancellable mixin

A mixin for making a class cancellable using a CancellationToken.

To implement this mixin on a custom cancellable:

  • Call maybeAttach to attach to the token before starting async work. If false is returned, the token has already been cancelled and no async operations should be started.
  • Override onCancel to handle cancellation.
  • Call detach after all async operations complete.

It's good practice to make any token parameters nullable to make cancellation optional.

class MyCancellable with Cancellable {
  MyCancellable(this.cancellationToken) {
    // Call `maybeAttach()` to only attach if the cancellation token hasn't
    // already been cancelled
    if (maybeAttach(this.cancellationToken)) {
      // Start your async task here
    }
  }

  final CancellationToken cancellationToken;

  @override
  void onCancel(Exception cancelException) {
    super.onCancel(exception);
    // Clean up resources here, like closing an HttpClient, and complete
    // any futures or streams
  }

  void complete() {
    // If your async task completes before the token is cancelled,
    // detatch from the token
    detach();
  }
}
Mixin Applications

Properties

cancellationStackTrace StackTrace
The stack trace at the time this cancellable was created.
final
hashCode int
The hash code for this object.
no setterinherited
isCancelled bool
Whether or not the operation has been cancelled.
no setter
runtimeType Type
A representation of the runtime type of the object.
no setterinherited

Methods

detach() → void
Detatches from the CancellationToken. This should be called after completing without cancellation.
maybeAttach(CancellationToken? token) bool
Attaches to the CancellationToken only if it hasn't already been cancelled. If the token has already been cancelled, onCancel is called instead.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
onCancel(Exception cancelException) → void
Called when the attached token is cancelled.
toString() String
A string representation of this object.
inherited

Operators

operator ==(Object other) bool
The equality operator.
inherited