Skip to content

Instantly share code, notes, and snippets.

@machinescream
Created May 13, 2020 21:07
Show Gist options
  • Save machinescream/c9dd83331e61dfb0719513cade67de65 to your computer and use it in GitHub Desktop.
Save machinescream/c9dd83331e61dfb0719513cade67de65 to your computer and use it in GitHub Desktop.
class Cancelable<O> implements Future {
final Completer<O> _completer;
final VoidCallback onCancel;
Cancelable(this._completer, this.onCancel);
void cancel() {
onCancel();
if (!_completer.isCompleted) _completer.completeError(CanceledError());
}
@override
Stream asStream() => _completer.future.asStream();
@override
Future catchError(Function onError, {bool Function(Object error) test}) =>
_completer.future.catchError(onError, test: test);
@override
Future<R> then<R>(Function(O value) onValue, {Function onError}) =>
_completer.future.then(onValue, onError: onError).catchError((e) {});
@override
Future timeout(Duration timeLimit, {FutureOr Function() onTimeout}) => _completer.future.timeout(timeLimit);
@override
Future whenComplete(FutureOr Function() action) => _completer.future.whenComplete(action);
}
class CanceledError implements Exception {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment