2

If you have a chain of futures like (taken from the Dart tutorial)

expensiveA().then((aValue) => expensiveB()) 
            .then((bValue) => expensiveC()) 
            .then((cValue) => doSomethingWith(cValue));

What is the right "Dart" way of canceling such a chain? For instance, this long chain could have been started some time ago and you want to be able to cancel it if the user takes an action that makes the final result useless.

One could have the code of expensiveA, expensiveB, expensiveC and doSomethingWith check for a variable value and throw an error in case the value has a certain value.

But is there a generic way to kill a chain of Futures?

References:

The dart tutorial gives an example on how to chain futures: https://www.dartlang.org/docs/tutorials/futures/#calling-multiple-funcs

There is question that is (imho) partially answered about how to cancel a future: is there any way to cancel a dart Future?

Community
  • 1
  • 1

1 Answers1

5

No. There is no way to cancel such a chain.

There are ways to simulate cancelable futures, though:

var someBool;

cancelIfSomeBoolIsSet(fun(x)) {
  return (x) {
    if (someBool) return new Completer().future;
    return fun(x);
  };
}

expensiveA().then(cancelIfSomeBoolIsSet(expensiveB))
            .then(cancelIfSomeBoolIsSet(expensiveC))
            .then(doSomethingWithCValue);

Once someBool is set, the future-chain is effectively canceled, because the completer's future is never completed.

Note: cancelIfSomeBoolIsSet takes a one-arg function in my example (contrary to the 0-arg function in the initial post). It would be trivial to adapt the code.

Florian Loitsch
  • 7,698
  • 25
  • 30
  • Thanks. But can that be considered a memory leak? – Laurent Ploix Jan 10 '14 at 09:14
  • No. Since nobody can reach the completer, the future and all its callbacks will get reclaimed. Of course, if someone points to a (non-completed) future, then that memory can not be reclaimed. This technique here would just increase the transitive amount of memory by a constant factor. – Florian Loitsch Jan 10 '14 at 17:14