Search code examples
dartdart-async

DART: How to write timeconsuming function returning a Future


I have to write a timeconsuming function that will return a Future, if it´s ready. Is the approach below correct, or does my timeconsuming algorithm in line 9 block the program til it´s ready. In this case, what would I have to do, to give control back to the eventloop or what else could be a solution?

Future<int> timeconsumingFunctionReturningFuture(int i) {
  var completer = new Completer();
 
  if (i==0) { 
    completer.completeError(88);
    return completer.future;
  } else {
    int rc;
    // Line9: rc = timeconsuming algorithm, to calculate rc
    completer.complete(rc);
    return completer.future;
  }
}

Solution

  • Your code probably wouldn't work as expected as your algorythm may block the returning of the completer. Try it this way:

    Future<int> timeconsumingFunctionReturningFuture(int i) {
      var completer = new Completer();
    
      if (i==0) { 
        completer.completeError(88);
      } else {
        Timer.run(() {
          int rc;
          // Line9: rc = timeconsuming algorithm, to calculate rc
          completer.complete(rc);
        });
      }
      return completer.future;
    }
    

    This way your timeconsuming algorithm runs asynchronously and the future is returned immediately.

    I have not tried it myself but this shorter version should also work (without creating a completer)

    return new Future.delayed(Duration.ZERO, () {
        // timeconsuming algorithm
      });