I try to cancel Future, but still getting the execution code in .then(). Why is it not working and what am I doing wrong?
var c = CancelableOperation.fromFuture(
Future.delayed(new Duration(seconds: 5), () {
}).then((data){
print("123"); // This code is always called...
})
);
c.cancel();
Cancelling a Future cancel() method. It attempts to cancel the execution of the task and returns true if it is cancelled successfully, otherwise, it returns false. The cancel() method accepts a boolean argument - mayInterruptIfRunning .
Many of you know that you can't cancel a Future in Dart, but you can cancel a subscription to a Stream. So one way you could handle this situation is to rewrite getData() to return a Stream instead. That may or may not be possible or desirable.
A Future represents the result of an asynchronous computation. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation.
https://pub.dartlang.org/packages/async
The
CancelableOperation
class defines an operation that can be canceled by its consumer. The producer can then listen for this cancellation and stop producing the future when it's received. It can be created using aCancelableCompleter
.
Especially this part
The producer can then listen for this cancellation and stop producing
So the producer of the value is supposed to stop doing work. This doesn't mean it won't return a result. It might return null
to indicate it is not an actual result.
What you want is probably the CancelableCompleter
instead.
The unit tests might be helpful understanding how these classes are supposed to be used
https://github.com/dart-lang/async/blob/1106a5bfee1472905711da7a78dcd413ba2f6dcf/test/cancelable_operation_test.dart#L93-L134 (and also the others in this file)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With