Dart:你如何让未来等待流



我想等待一个布尔值为真,然后从未来返回,但我似乎无法让我的未来等待流。

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);
}

没有流方法的替代实现可以在流上使用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;
}

最新更新