When you are interested in only the first emission, you want to use take
. Maybe you want to see what the user first clicked on when they entered the page, or you would want to subscribe to the click event and just take the first emission. Another use-case is when you need to take a snapshot of data at a particular point in time but do not require further emissions. For example, a stream of user token updates, or a route guard based on a stream in an Angular application.
π‘ If you want to take a variable number of values based on some logic, or another observable, you can use takeUntil or takeWhile!
π‘ take
is the opposite of skip
where take
will take the first n number of emissions while skip
will skip the first n number of emissions.
ββββ
Example 1: Take 1 value from source
( StackBlitz | jsBin | jsFiddle )
// RxJS v6+import { of } from 'rxjs';import { take } from 'rxjs/operators';β//emit 1,2,3,4,5const source = of(1, 2, 3, 4, 5);//take the first emitted value then completeconst example = source.pipe(take(1));//output: 1const subscribe = example.subscribe(val => console.log(val));
Example 2: Take the first 5 values from source
( StackBlitz | jsBin | jsFiddle )
// RxJS v6+import { interval } from 'rxjs';import { take } from 'rxjs/operators';β//emit value every 1sconst interval$ = interval(1000);//take the first 5 emitted valuesconst example = interval$.pipe(take(5));//output: 0,1,2,3,4const subscribe = example.subscribe(val => console.log(val));
Example 3: Taking first click location
(StackBlitz | jsFiddle)
<div id="locationDisplay">Where would you click first?</div>
// RxJS v6+import { fromEvent } from 'rxjs';import { take, tap } from 'rxjs/operators';βconst oneClickEvent = fromEvent(document, 'click').pipe(take(1),tap(v => {document.getElementById('locationDisplay').innerHTML = `Your first click was on location ${v.screenX}:${v.screenY}`;}));βconst subscribe = oneClickEvent.subscribe();
βBattleship Gameβ
βMemory Gameβ
βtake π° - Official docs
βtake - In Depth Dev Reference
βFiltering operator: take, first, skipβ
π₯ π΅ - AndrΓ© Staltz
βBuild your own take operatorβ
π₯ - Kwinten Pisman
π Source Code: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/take.tsβ