Finds the first element of this stream matching test
.
Returns a future that is filled with the first element of this stream
that test
returns true for.
If no such element is found before this stream is done, and a
defaultValue
function is provided, the result of calling defaultValue
becomes the value of the future.
Stops listening to the stream after the first matching element has been received.
Internally the method cancels its subscription after the first element that matches the predicate. This means that single-subscription (non-broadcast) streams are closed and cannot be reused after a call to this method.
If an error occurs, or if this stream ends without finding a match and
with no defaultValue
function provided, the future will receive an
error.
Source
Future<dynamic> firstWhere(bool test(T element), {Object defaultValue()}) {
_Future<dynamic> future = new _Future();
StreamSubscription subscription;
subscription = this.listen(
(T value) {
_runUserCode(
() => test(value),
(bool isMatch) {
if (isMatch) {
_cancelAndValue(subscription, future, value);
}
},
_cancelAndErrorClosure(subscription, future)
);
},
onError: future._completeError,
onDone: () {
if (defaultValue != null) {
_runUserCode(defaultValue, future._complete, future._completeError);
return;
}
try {
throw IterableElementError.noElement();
} catch (e, s) {
_completeWithErrorCallback(future, e, s);
}
},
cancelOnError: true);
return future;
}