On this page
single
function
stable
operator
Returns an observable that asserts that only one value is emitted from the observable that matches the predicate. If no predicate is provided, then it will assert that the observable only emits one value.
single<T>(predicate?: (value: T, index: number, source: Observable<T>) => boolean): MonoTypeOperatorFunction<T>
Parameters
predicate |
(value: T, index: number, source: Observable<T>) => boolean |
Optional. Default is A predicate function to evaluate items emitted by the source Observable. |
Returns
MonoTypeOperatorFunction<T>
: A function that returns an Observable that emits the single item emitted by the source Observable that matches the predicate.
Throws
NotFoundError
Delivers an NotFoundError to the Observer's error
callback if the Observable completes before any next
notification was sent.
SequenceError
Delivers a SequenceError if more than one value is emitted that matches the provided predicate. If no predicate is provided, will deliver a SequenceError if more than one value comes from the source
Description
In the event that the observable is empty, it will throw an EmptyError
.
In the event that two values are found that match the predicate, or when there are two values emitted and no predicate, it will throw a SequenceError
In the event that no values match the predicate, if one is provided, it will throw a NotFoundError
Example
Expect only name
beginning with 'B'
import { of, single } from 'rxjs';
const source1 = of(
{ name: 'Ben' },
{ name: 'Tracy' },
{ name: 'Laney' },
{ name: 'Lily' }
);
source1
.pipe(single(x => x.name.startsWith('B')))
.subscribe(x => console.log(x));
// Emits 'Ben'
const source2 = of(
{ name: 'Ben' },
{ name: 'Tracy' },
{ name: 'Bradley' },
{ name: 'Lincoln' }
);
source2
.pipe(single(x => x.name.startsWith('B')))
.subscribe({ error: err => console.error(err) });
// Error emitted: SequenceError('Too many values match')
const source3 = of(
{ name: 'Laney' },
{ name: 'Tracy' },
{ name: 'Lily' },
{ name: 'Lincoln' }
);
source3
.pipe(single(x => x.name.startsWith('B')))
.subscribe({ error: err => console.error(err) });
// Error emitted: NotFoundError('No values match')
See Also
© 2015–2022 Google, Inc., Netflix, Inc., Microsoft Corp. and contributors.
Code licensed under an Apache-2.0 License. Documentation licensed under CC BY 4.0.
https://rxjs.dev/api/index/function/single