Dart:如何让 Future 等待 Stream?

Dart: How do you make a Future wait for a Stream?

我想等待 bool 为真,然后 return 来自 Future,但我似乎无法让我的 Future 等待 Stream。

Future<bool> ready() {
  return new Future<bool>(() {
    StreamSubscription readySub;
    _readyStream.listen((aBool) {
      if (aBool) {
        return true;
      }
    });
  });
}

您可以使用 Stream 方法 firstWhere 创建一个在您的 Stream 发出 true 值时解析的未来。

Future<bool> whenTrue(Stream<bool> source) {
  return source.firstWhere((bool item) => item);
}

没有流方法的替代实现可以在 Stream 上使用 await for 语法。

Future<bool> whenTrue(Stream<bool> source) async {
  await for (bool value in source) {
    if (value) {
      return value;
    }
  }
  // stream exited without a true value, maybe return an exception.
}
Future<void> _myFuture() async {
  Completer<void> _complete = Completer();
  Stream.value('value').listen((event) {}).onDone(() {
    _complete.complete();
  });
  return _complete.future;
}