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

2

32

I would like to wait for a bool to be true, then return from a Future, but I can't seem to make my Future to wait for the Stream.

Future<bool> ready() {
  return new Future<bool>(() {
    StreamSubscription readySub;
    _readyStream.listen((aBool) {
      if (aBool) {
        return true;
      }
    });
  });
}
Phyllome answered 8/4, 2018 at 22:16 Comment(0)
F
52

You can use the Stream method firstWhere to create a future that resolves when your Stream emits a true value.

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

An alternative implementation without the stream method could use the await for syntax on the Stream.

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.
}
Fp answered 8/4, 2018 at 23:0 Comment(2)
Do we have to create a future builder for it?Nonce
there is also .asFuture() on .listen() method if you want to use a 3rd option :)Feel
E
5
Future<void> _myFuture() async {
  Completer<void> _complete = Completer();
  Stream.value('value').listen((event) {}).onDone(() {
    _complete.complete();
  });
  return _complete.future;
}
Eldwun answered 28/1, 2022 at 6:41 Comment(1)
Your answer could be improved by adding more information on what the code does and how it helps the OP.Concoction

© 2022 - 2024 — McMap. All rights reserved.