检查未来是否完成

Blu*_*nce 6 dart

在“ m3”之前,您可以检查“ Future”是否已用“ completer.future.isComplete”完成,这似乎已经消失了。有替代品吗?还是我需要自己保存它(似乎在_CompleterImpl内仍然有一个字段'_isComplete',但未公开

Cut*_*tch 8

使用 M3 Dart,最好只使用您自己的标志。

future.whenComplete() {
  tweenCompleted = true;
}
Run Code Online (Sandbox Code Playgroud)

Dart 是一种单线程语言,因此这里没有竞争条件。请注意,[action] 函数在此 future 完成时被调用,无论是使用值还是错误。

  • 你没有错@raiym - 自从发布这个问题以来,语言已经发生了一些变化,现在该方法被称为“whenComplete”。 (2认同)

Hug*_*sos 7

@Cutch解决方案的替代方案是FutureCompleter

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
  }
}
Run Code Online (Sandbox Code Playgroud)

这种方法更加灵活,因为您既可以异步等待完成,又可以检查 future 是否同步完成。


JJ *_*sis 7

使用 Future 的扩展并以 Hugo Passos 的答案为基础:

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;
  }
}
Run Code Online (Sandbox Code Playgroud)