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;
}
});
});
}
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.
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.
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.
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.
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.
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.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With