is there any way to cancel a dart Future?

后端 未结 9 1500
礼貌的吻别
礼貌的吻别 2020-11-27 05:55

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 a

9条回答
  •  情歌与酒
    2020-11-27 06:22

    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() {
      _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.

提交回复
热议问题