Not canceled Future
Asked Answered
S

1

6

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();
Syphon answered 12/12, 2018 at 8:1 Comment(0)
D
7

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)

Davisson answered 12/12, 2018 at 8:4 Comment(1)
And as to why you can't cancel Future: A Future does not represent a computation. It represents the result of a computation. That makes futures safe to share - you can pass a future to anyone, and to multiple people, without giving them a way to interfere with the operation. The classes mentioned above are there to represent the operation itself (and they then contain a future representing the result).Squireen

© 2022 - 2024 — McMap. All rights reserved.