Jus10
Jus10

Reputation: 15699

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

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

Upvotes: 33

Views: 20781

Answers (2)

Jhionan Santos
Jhionan Santos

Reputation: 342

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

Upvotes: 5

Jonah Williams
Jonah Williams

Reputation: 21451

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.
}

Upvotes: 53

Related Questions