Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Future is complete

Tags:

dart

Before 'm3' you could check if a Future was completed with 'completer.future.isComplete' this seems to be gone. Is there a replacement? or do I need to save it myself then (it seems inside the _CompleterImpl there is still a field '_isComplete' but its not exposed

like image 685
Bluenuance Avatar asked Jan 24 '13 08:01

Bluenuance


3 Answers

An alternative to @Cutch's solution is to wrap the Future in a Completer:

Completer<T> wrapInCompleter<T>(Future<T> future) {
  final completer = Completer<T>();
  future.then(completer.complete).catchError(completer.completeError);
  return completer;
}

Future<void> main() async {
  final completer = wrapInCompleter(asyncComputation());
  if (completer.isCompleted) {
    final result = await completer.future;
    // do your stuff
  }
}

This approach is more resourceful since you can both await for the completion asynchronously and check whether the future is completed synchronously.

like image 199
Hugo Passos Avatar answered Nov 12 '22 02:11

Hugo Passos


With M3 Dart, it's best to just use your own flag.

future.whenComplete(() {
  tweenCompleted = true;
});

Dart is a single threaded language so there is no race condition here. Note that the [action] function is called when this future completes, whether it does so with a value or with an error.

like image 13
Cutch Avatar answered Nov 12 '22 03:11

Cutch


Using an extension on Future and building on Hugo Passos' answer:

extension FutureExtension<T> on Future<T> {
  /// Checks if the future has returned a value, using a Completer.
  bool isCompleted() {
    final completer = Completer<T>();
    then(completer.complete).catchError(completer.completeError);
    return completer.isCompleted;
  }
}
like image 3
JJ Du Plessis Avatar answered Nov 12 '22 03:11

JJ Du Plessis