take

signature: take(count: number): Observable

Emit provided number of values before completing.

Why use take

When you are interested in only the first set number of emission, you want to
use take. Maybe you want to see what the user first clicked on when he/she
first entered the page, you would want to subscribe to the click event and just
take the first emission. There is a race and you want to observe the race, but
you’re only interested in the first who crosses the finish line. This operator
is clear and straight forward, you just want to see the first n numbers of
emission to do whatever it is you need.


:bulb: If you want to take a variable number of values based on some logic, or
another observable, you can use takeUntil or
takeWhile!

:bulb: 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.


take - 图3

Examples

Example 1: Take 1 value from source

( jsBin |
jsFiddle )

  1. import { of } from 'rxjs/observable/of';
  2. import { take } 'rxjs/operators';
  3. //emit 1,2,3,4,5
  4. const source = of(1, 2, 3, 4, 5);
  5. //take the first emitted value then complete
  6. const example = source.pipe(take(1));
  7. //output: 1
  8. const subscribe = example.subscribe(val => console.log(val));
Example 2: Take the first 5 values from source

( jsBin |
jsFiddle )

  1. import { interval } from 'rxjs/observable/interval';
  2. import { take } 'rxjs/operators';
  3. //emit value every 1s
  4. const interval = interval(1000);
  5. //take the first 5 emitted values
  6. const example = interval.pipe(take(5));
  7. //output: 0,1,2,3,4
  8. const subscribe = example.subscribe(val => console.log(val));
Example 3: Taking first click loclation

(jsFiddle)

  1. <div id="locationDisplay">
  2. Where would you click first?
  3. </div>
  1. import { fromEvent } from 'rxjs/observable/fromEvent';
  2. import { take, tap } 'rxjs/operators';
  3. const oneClickEvent = fromEvent(document, 'click').pipe(
  4. take(1),
  5. tap(v => {
  6. document.getElementById('locationDisplay').innerHTML
  7. = `Your first click was on location ${v.screenX}:${v.screenY}`;
  8. })
  9. )
  10. const subscribe = oneClickEvent.subscribe();

Additional Resources


:file_folder: Source Code:
https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/take.ts