single property
The single element of this stream.
If this stream emits an error event, the returned future is completed with that error and processing stops.
If this Stream is empty or has more than one element, the returned future completes with an error.
Implementation
Future<T> get single {
_Future<T> future = new _Future<T>();
late T result;
bool foundResult = false;
StreamSubscription<T> subscription = this.listen(
null,
onError: future._completeError,
onDone: () {
if (foundResult) {
future._complete(result);
return;
}
var stack = StackTrace.empty;
var error = IterableElementError.noElement();
_trySetStackTrace(error, stack);
_completeWithErrorCallback(future, error, stack);
},
cancelOnError: true,
);
subscription.onData((T value) {
if (foundResult) {
// This is the second element we get.
var stack = StackTrace.empty;
var error = IterableElementError.tooMany();
_trySetStackTrace(error, stack);
_cancelAndErrorWithReplacement(subscription, future, error, stack);
return;
}
foundResult = true;
result = value;
});
return future;
}