is there any way to cancel a dart Future?

2019-01-19 05:44发布

In a Dart UI, I have a button [submit] to launch a long async request. The [submit] handler returns a Future. Next, the button [submit] is replaced by a button [cancel] to allow the cancellation of the whole operation. In the [cancel] handler, I would like to cancel the long operation. How can I cancel the Future returned by the submit handler? I found no method to do that.

3条回答
啃猪蹄的小仙女
2楼-- · 2019-01-19 05:57

As far as I know, there isn't a way to cancel a Future. But there is a way to cancel a Stream subscription, and maybe that can help you.

Calling onSubmit on a button returns a StreamSubscription object. You can explicitly store that object and then call cancel() on it to cancel the stream subscription:

StreamSubscription subscription = someDOMElement.onSubmit.listen((data) {

   // you code here

   if (someCondition == true) {
     subscription.cancel();
   }
});

Later, as a response to some user action, perhaps, you can cancel the subscription:

查看更多
欢心
3楼-- · 2019-01-19 06:03

Change the future's task from 'do something' to 'do something unless it has been cancelled'. An obvious way to implement this would be to set a boolean flag and check it in the future's closure before embarking on processing, and perhaps at several points during the processing.

Also, this seems to be a bit of a hack, but setting the future's timeout to zero would appear to effectively cancel the future.

查看更多
Luminary・发光体
4楼-- · 2019-01-19 06:09

One way I accomplished to 'cancel' a scheduled execution was using a Timer. In this case I was actually postponing it. :)

Timer _runJustOnceAtTheEnd;

void runMultipleTimes() {
  if (_runJustOnceAtTheEnd != null) {
    _runJustOnceAtTheEnd.cancel();
    _runJustOnceAtTheEnd = null;
  }

  // do your processing

  _runJustOnceAtTheEnd = Timer(Duration(seconds: 1), onceAtTheEndOfTheBatch);
}

void onceAtTheEndOfTheBatch() {
  print("just once at the end of a batch!");
}


runMultipleTimes();
runMultipleTimes();
runMultipleTimes();
runMultipleTimes();

// will print 'just once at the end of a batch' one second after last execution

The runMultipleTimes() method will be called multiple times in sequence, but only after 1 second of a batch the onceAtTheEndOfTheBatch will be executed.

查看更多
登录 后发表回答