take
The take operator forwards values emitted by the source observable to the observer, acting as a mirror, until a predefined count of emissions has been delivered.
For each incoming value, take checks how many values have already been forwarded against the set limit. Once that limit is hit, it terminates the stream: the operator unsubscribes from the source and sends a complete notification downstream.
The behavior of take can be broken down into these steps:
- Subscribe to the source observable.
- On each emission from the source, relay the value to the observer.
- Increment the emission counter and check it against the configured limit.
- When the counter matches the limit, unsubscribe from the source and emit a complete notification.
- If the source finishes on its own, propagate the complete notification.
- If the source signals an error, pass the error notification along.
Usage
A typical scenario for take involves pulling a value from an observable-backed storage. When working with a global store built on observables—such as NgRx or Redux-observable—you often need to read a slice of that state in a synchronous or one-off manner.
The snippet below demonstrates this pattern with the take operator:
const store = new BehaviorSubject(1);
// since store here is implemented as a Subject and doesn't complete,
// and if we don't use `take(1)`, the subscription is kept forever
store.pipe(take(1)).subscribe((v) => console.log(v));
