Search code examples
dartdart-async

Execute Futures until a parameter becomes true


I launch a request to a server with a future "requestServer". I would like to poll a system for a specific value (passed from false to true, when request is done) and return when finished.

Code could be like that, but "while" synchronous and "checkOperation" is asynchronous?

return requestServer().then((operation) {
  var done = false;
  while (done)
    return checkOperation(operation).then((result) {
      done = (result == true);
    });
    sleep(10);
  }
});

Any ideas ?


Solution

  • I guess this is not exactly what you want but as far as I know there is no way to block execution so you have to use callbacks.

    void main(List<String> args) {
    
      // polling
      new Timer.periodic(new Duration(microseconds: 100), (t) {
        if(isDone) {
          t.cancel();
          someCallback();
        }
      });
    
      // set isDone to true sometimes in the future
      new Future.delayed(new Duration(seconds: 10), () => isDone = true);
    }
    
    bool isDone = false;
    
    void someCallback() {
      print('isDone: $isDone');
      // continue processing
    }
    

    You can of course pass the callback as parameter instead of hardcode it, because functions are first class members in Dart.