RxJS 배우기
  • 소개
  • RxJS 배우기
    • 연산자
      • Combination
        • combineAll
        • combineLatest
        • concat
        • concatAll
        • endWith
        • forkJoin
        • merge
        • mergeAll
        • pairwise
        • race
        • startWith
        • withLatestFrom
        • zip
      • Conditional
        • defaultIfEmpty
        • every
        • iif
        • sequenceEqual
      • Creation
        • ajax
        • create
        • defer
        • empty
        • from
        • fromEvent
        • generate
        • interval
        • of
        • range
        • throw
        • timer
      • Error Handling
        • catch / catchError
        • retry
        • retryWhen
      • Multicasting
        • publish
        • multicast
        • share
        • shareReplay
      • Filtering
        • audit
        • auditTime
        • debounce
        • debounceTime
        • distinct
        • distinctUntilChanged
        • distinctUntilKeyChanged
        • filter
        • find
        • first
        • ignoreElements
        • last
        • sample
        • single
        • skip
        • skipUntil
        • skipWhile
        • take
        • takeLast
        • takeUntil
        • takeWhile
        • throttle
        • throttleTime
      • Transformation
        • buffer
        • bufferCount
        • bufferTime
        • bufferToggle
        • bufferWhen
        • concatMap
        • concatMapTo
        • exhaustMap
        • expand
        • groupBy
        • map
        • mapTo
        • mergeMap / flatMap
        • mergeScan
        • partition
        • pluck
        • reduce
        • scan
        • switchMap
        • switchMapTo
        • toArray
        • window
        • windowCount
        • windowTime
        • windowToggle
        • windowWhen
      • Utility
        • tap / do
        • delay
        • delayWhen
        • dematerialize
        • finalize / finally
        • let
        • repeat
        • timeInterval
        • timeout
        • timeoutWith
        • toPromise
      • 전체 목록
    • Subjects
      • AsyncSubject
      • BehaviorSubject
      • ReplaySubject
      • Subject
    • 사용예시
      • Alphabet Invasion Game
      • Battleship Game
      • Breakout Game
      • Car Racing Game
      • Catch The Dot Game
      • Click Ninja Game
      • Flappy Bird Game
      • Game Loop
      • Horizontal Scroll Indicator
      • Http Polling
      • Lockscreen
      • Matrix Digital Rain
      • Memory Game
      • Mine Sweeper Game
      • Platform Jumper Game
      • Progress Bar
      • Save Indicator
      • Smart Counter
      • Space Invaders Game
      • Stop Watch
      • Swipe To Refresh
      • Tank Battle Game
      • Tetris Game
      • Type Ahead
      • Uncover Image Game
    • 개념
      • RxJS 입문서
      • RxJS v5 -> v6 업그레이드
      • 시간 기반의 연산자 비교
      • 연산자 imports의 이해
Powered by GitBook
On this page
  • 제공된 수 만큼의 값만 발생시키고 종료합니다.
  • 왜 take 를 사용할까요?
  • 예시
  • 관련 사용법
  • 추가 자료

Was this helpful?

  1. RxJS 배우기
  2. 연산자
  3. Filtering

take

PreviousskipWhileNexttakeLast

Last updated 5 years ago

Was this helpful?

signature: take(count: number): Observable

제공된 수 만큼의 값만 발생시키고 종료합니다.

왜 take 를 사용할까요?

만약 여러분이 첫번째로 발생한 값만을 원한다면, take 를 사용하세요. 여러분은 사용자가 페이지에 들어와서 처음 클릭한 내용을 확인하거나, 클릭 이벤트를 구독한 뒤 가장 처음 발생한 값만을 보고싶을 수 있습니다. 또 다른 사례는 특정 시점에서 데이터 스냅샷을 작성해야 하지만, 이후 추가적인 값 발생은 원하지 않는 경우입니다. 예를 들어, 사용자 토큰 업데이트의 스트림이나, 앵귤러 애플리케이션에서의 라우트 가드 기반의 스트림이 있습니다.

만약 여러분이 특정 로직이나, 다른 옵저버블을 기반으로 여러 값들을 받고싶다면, 이나 를 확인해보세요!

take 는 첫 n개의 값만 발생시키는 반면, 정반대인 은 첫 n개의 값을 건너뛰고 값을 발생시킵니다.

예시

예시 1: 소스로부터 1개의 값만 받기

( | | )

// RxJS v6+
import { of } from 'rxjs';
import { take } from 'rxjs/operators';

//1,2,3,4,5를 발생시킵니다
const source = of(1, 2, 3, 4, 5);
//발생된 값 중 첫번째 값만 받고 종료시킵니다.
const example = source.pipe(take(1));
//결과: 1
const subscribe = example.subscribe(val => console.log(val));

예시 2: 소스로부터 첫 5개의 값만 받기

// RxJS v6+
import { interval } from 'rxjs';
import { take } from 'rxjs/operators';

//매 1초마다 값을 발생시킵니다
const interval$ = interval(1000);
//발생된 값 중 첫 5개의 값만 받습니다
const example = interval$.pipe(take(5));
//결과: 0,1,2,3,4
const subscribe = example.subscribe(val => console.log(val));

예시 3: 첫번째 클릭 위치를 받기

<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();

관련 사용법

추가 자료

( | | )

( | )

- 공식 문서

- André Staltz

- Kwinten Pisman

Source Code:

💡
💡
takeUntil
takeWhile
skip
StackBlitz
jsBin
jsFiddle
StackBlitz
jsBin
jsFiddle
StackBlitz
jsFiddle
Battleship Game
Memory Game
📰
take
📹
💵
Filtering operator: take, first, skip
📹
Build your own take operator
📂
https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/take.ts