operator

lee jae hwan·2022년 8월 30일
0

RxJS

목록 보기
3/21

ajax

signature: ajax(urlOrRequest: string | AjaxRequest)

URL, 헤더 등을 사용하여 요청 객체를 사용하거나 URL의 문자열을 사용하여 Ajax 요청에 대한 옵저버블을 생성합니다.

import { ajax } from 'rxjs/ajax';

const githubUsers = `https://api.github.com/users?per_page=2`;

const users = ajax(githubUsers);

const subscribe = users.subscribe(
  res => console.log(res),
  err => console.error(err)
);
import { ajax } from 'rxjs/ajax';

const githubUsers = `https://api.github.com/users?per_page=2`;

const users = ajax.getJSON(githubUsers);

const subscribe = users.subscribe(
  res => console.log(res),
  err => console.error(err)
);

bufferTime

제공된 시간이 지날 때까지 방출 된 값을 수집하고 배열로 방출합니다.

signature: bufferTime(bufferTimeSpan: number, bufferCreationInterval: number, scheduler: Scheduler): Observable

import { interval } from 'rxjs';
import { bufferTime } from 'rxjs/operators';

//Create an observable that emits a value every 500ms
const source = interval(500);
//After 2 seconds have passed, emit buffered values as an array
const example = source.pipe(bufferTime(2000));
//Print values to console
//ex. output [0,1,2]...[3,4,5,6]
const subscribe = example.subscribe(val =>
  console.log('Buffered with Time:', val)
);

**map**

map(project: Function, thisArg: any): Observable

각각의 값에 넘겨받은 콜백을 적용합니다

import { from } from 'rxjs';
import { map } from 'rxjs/operators';

const stream = from([
      { name: 'Joe', age: 30 },
      { name: 'Frank', age: 20 },
      { name: 'Ryan', age: 50 }
    ]);
 stream.pipe(map(({name})=>name)).subscribe(console.log);

merge

merge(input: Observable): Observable

여러 관측 가능 항목을 하나의 관찰 가능한 항목으로 변환합니다.

    //emit every 2.5 seconds
    const first = interval(2500);
    //emit every 2 seconds
    const second = interval(2000);
    //emit every 1.5 seconds
    const third = interval(1500);
    //emit every 1 second
    const fourth = interval(1000);

    //emit outputs from one observable
    const example = merge(
      first.pipe(map(() => 'FIRST!')),
      second.pipe(map(() => 'second!')),
      third.pipe(map(() => 'third!')),
      fourth.pipe(map(() => 'fourth!'))
    );
    //output: "FOURTH", "THIRD", "SECOND!", "FOURTH", "FIRST!", "THIRD", "FOURTH"
    const subscribe = example.subscribe((val) => console.log(val));

first

첫 번째 값 1개만 발행하고 더 이상 값을 발행하지 않는(complete 함수를 호출하는) 연산자

import { range, pipe } from 'rxjs'
import { first } from 'rxjs/operators'

range(1,10).pipe(first((value,index)=>index==3 || value==1)).subscribe(console.log)

**last**

마지막 값 1개만 발행하는 연산자다. 마찬가지로 complete함수를 호출한다.

range(1,10).pipe(last((value,index)=>index==3 || value==1)).subscribe(console.log)

**take**

정해진 개수만큼 구독하고 구독을 해제한다.

range(1,10).pipe(take(5)).subscribe(console.log)

**takeUntil**

특정 이벤트가 발생할 때까지 옵저버블을 구독해야 한다면 이 연산자가 유용하다.

    const sourceStream = interval(1000);
    const stream = fromEvent(document,'click')
    sourceStream.pipe(takeUntil(stream)).subscribe(console.log)

takelast

마지막에 발행한 값을 기준으로 인수로 설정한 수만큼 값을 발행하고 complete 함수를 호출한다

    const stream = of('Ignore', 'Ignore', 'Hello', 'World!');
    stream.pipe(takeLast(2)).subscribe(console.log)

skip

인수(argument)에 숫자를 넣으면 해당 숫자만큼 값들을 건너뛰고 그 다음부터 값을 발행한 후에 complete 함수를 호출한다.

const stream = range(1,10).pipe(skip(3)).subscribe(console.log)

skipUntil

takeUntil처럼 옵저버블을 인자로 사용하지만 인자로 사용한 옵저버블의 값 발행을 시작할 때까지 소스 옵저버블에서 발행하는 값을 건너뛴다.

    interval(1000).pipe(
      skipUntil(interval(5000)),
      take(3)
    ).subscribe(console.log)

skipWhile

predicate 함수의 조건에 만족할 때 값 발행을 건너뛴다. 조건을 만족하지 않으면 조건과 상관없이 계속 값을 발행한다.

    interval(1000).pipe(
      skipWhile(x=>x>4),
      take(3)
    ).subscribe(console.log)

debounce

    const clicks = fromEvent(document, 'click');
    const result = clicks.pipe(
      scan((i) => ++i, 1),
      debounce((i) => interval(200 * i))
    );
    result.subscribe((x) => console.log(x));

0개의 댓글