Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top