Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not canceled Future

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();
like image 623
Anton Maximkin Avatar asked Dec 12 '18 08:12

Anton Maximkin


People also ask

What is Future 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 .

How do you cancel a Future in darts?

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.

What is Future Java?

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.


1 Answers

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 a CancelableCompleter.

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)

like image 136
Günter Zöchbauer Avatar answered Sep 26 '22 19:09

Günter Zöchbauer