Reputation: 4308
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;
}
}
Upvotes: 3
Views: 190
Reputation: 8128
Günter Zöchbauer's solution is correct, but you can simplify the code:
Future<int> timeconsumingFunctionReturningFuture(int i) {
if (i == 0) return new Future.error(88);
return new Future(() {
int rc;
// Line9: rc = timeconsuming algorithm, to calculate rc
return rc;
});
}
Alternatively you can even put the error-check into the Future:
Future<int> timeconsumingFunctionReturningFuture(int i) {
return new Future(() {
if (i == 0) throw 88;
int rc;
// Line9: rc = timeconsuming algorithm, to calculate rc
return rc;
});
}
Also note: if passing 0 for i
is an error (programmer error), then throwing synchronously is usually ok. It would then behave the same way as passing in a string in checked mode.
Upvotes: 2
Reputation: 658235
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
});
Upvotes: 3