Dart:你如何让未来等待流?

Jus*_*s10 5 future stream dart

我想等一个bool是真的,然后从Future返回,但我似乎无法让我的Future等待Stream.

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

Jon*_*ams 11

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

Future<bool> whenTrue(Stream<bool> source) {
  return source.firstWhere((bool item) => item);
}
Run Code Online (Sandbox Code Playgroud)

没有stream方法的替代实现可以使用await forStream上的语法.

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


Jhi*_*tos 5

Future<void> _myFuture() async {
  Completer<void> _complete = Completer();
  Stream.value('value').listen((event) {}).onDone(() {
    _complete.complete();
  });
  return _complete.future;
}
Run Code Online (Sandbox Code Playgroud)

  • 通过添加更多有关代码的作用以及它如何帮助操作员的信息,可以改进您的答案。 (2认同)