Skip to content

Instantly share code, notes, and snippets.

@MariaMelnik
Created June 17, 2022 09:45
Show Gist options
  • Select an option

  • Save MariaMelnik/1bee0d73920548cf9cfc143c39ec49d2 to your computer and use it in GitHub Desktop.

Select an option

Save MariaMelnik/1bee0d73920548cf9cfc143c39ec49d2 to your computer and use it in GitHub Desktop.
dart: stop future with CancelableOperation
import 'package:async/async.dart';
void main() async {
final cancellableOperation = CancelableOperation.fromFuture(operation());
cancellableOperation.then((p0) => print('cancelable operation finished normally'),
onCancel: () => print('cancelable operation was canceled'));
await Future.delayed(Duration(seconds: 1)).then((_) {
cancellableOperation.cancel();
print('operation cancelled');
});
}
Future<void> operation() async {
await Future.delayed( Duration(seconds: 1));
print('1');
await Future.delayed( Duration(seconds: 1));
print('2');
await Future.delayed( Duration(seconds: 1));
print('3');
await Future.delayed( Duration(seconds: 1));
print('4');
await Future.delayed( Duration(seconds: 1));
print('5');
}
@MariaMelnik

Copy link
Copy Markdown
Author

you can't stop function execution with CancelableOperation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment