Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
      }
    });
  });
}
like image 945
Jus10 Avatar asked Apr 08 '18 22:04

Jus10


People also ask

How do you wait for Future to complete Dart?

Sometimes you need to have results of multiple async functions before starting to work on something else. To prevent multiple awaits, chaining futures in . then(), you can simply use Future. wait([]) that returns an array of results you were waiting for.

How do you use Future wait in flutter?

According to the flutter docs, Future. wait() : Returns a future which will complete once all the provided futures have completed, either with their results, or with an error if any of the provided futures fail. In the JavaScript world, this is achievable with Promise.

How do you create a Future variable in darts?

To create a Future object, we need to instantiate Future class by passing an invoker function (usually an anonymous function or fat arrow function) whose job is to return a value or another Future object that returns a value. A Future object has then and catchError methods which are used to register callback functions.

What is Future and stream in Dart?

A Future represents a computation that doesn't complete immediately. Where a normal function returns the result, an asynchronous function returns a Future, which will eventually contain the result. The future will tell you when the result is ready. A stream is a sequence of asynchronous events.

What is Future and stream in flutter?

A Future represents a one-time value: the app performs an operation and comes back with some data. A Stream represents a sequence of data. For example, you can use a Future to get the entire contents of a file or use a Stream to get the contents a line at a time.


1 Answers

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.
}
like image 61
Jonah Williams Avatar answered Oct 06 '22 00:10

Jonah Williams