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
  • Reduce해나갑니다.
  • 예시
  • 관련된 사용법
  • 추가 자료

Was this helpful?

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

scan

PreviousreduceNextswitchMap

Last updated 4 years ago

Was this helpful?

signature: scan(accumulator: function, seed: any): Observable

Reduce해나갑니다.

scan을 활용하여 스러운 상태관리를 할 수 있습니다!

예시

예시 1: 더해나갑니다.

( )

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

const source = of(1, 2, 3);
// 간단한 scan 예시로, 0부터 시작해서 더해나갑니다.
const example = source.pipe(scan((acc, curr) => acc + curr, 0));
// 누적된 값을 기록합니다.
// output: 1,3,6
const subscribe = example.subscribe(val => console.log(val));

예시 2: 객체에서 사용하기

// RxJS v6+
import { Subject } from 'rxjs';
import { scan } from 'rxjs/operators';

const subject = new Subject();
// 객체를 만들어나가는 scan 예시
const example = subject.pipe(
  scan((acc, curr) => Object.assign({}, acc, curr), {})
);
//누적된 값을 기록합니다.
const subscribe = example.subscribe(val =>
  console.log('Accumulated object:', val)
);
// subject로 다음 값을 넘겨주고, 객체의 프로퍼티로 추가합니다
// {name: 'Joe'}
subject.next({ name: 'Joe' });
// {name: 'Joe', age: 30}
subject.next({ age: 30 });
// {name: 'Joe', age: 30, favoriteLanguage: 'JavaScript'}
subject.next({ favoriteLanguage: 'JavaScript' });

예시 3: 누적된 배열에서 무작위 값을 내보냅니다.

// RxJS v6+
import { interval } from 'rxjs';
import { scan, map, distinctUntilChanged } from 'rxjs/operators';

// 배열에 값을 누적시키고, 무작위 값을 꺼냅니다.
const scanObs = interval(1000)
  .pipe(
    scan((a, c) => [...a, c], []),
    map(r => r[Math.floor(Math.random() * r.length)]),
    distinctUntilChanged()
  )
  .subscribe(console.log);

예시 4: http 응답을 누적시킵니다

// RxJS v6+
import { interval, of } from 'rxjs';
import { scan, delay, repeat, mergeMap } from 'rxjs/operators';

const fakeRequest = of('response').pipe(delay(2000));

// 결과:
// ['response'],
// ['response','response'],
// ['response','response','response'],
// etc...

interval(1000)
  .pipe(
    mergeMap(_ => fakeRequest),
    scan<string>((all, current) => [...all, current], [])
  )
  .subscribe(console.log);

관련된 사용법

추가 자료

( | | )

( )

( )

- 공식 문서

- Ben Lesh

- John Linquist

- André Staltz

- Kwinten Pisman

Source Code:

💡
Redux
StackBlitz
StackBlitz
jsBin
jsFiddle
StackBlitz
StackBlitz
Alphabet Invasion Game
Battleship Game
Breakout Game
Car Racing Game
Catch The Dot Game
Click Ninja Game
Flappy Bird Game
Matrix Digital Rain
Memory Game
Platform Jumper Game
Progress Bar
Smart Counter
Space Invaders Game
Stop Watch
Tank Battle Game
Tetris Game
Uncover Image Game
📰
scan
📹
Aggregating streams with reduce and scan using RxJS
📹
💵
Updating data with scan
📹
💵
Transformation operator: scan
📹
Build your own scan operator
📂
https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/scan.ts