scan
signature: scan(accumulator: function, seed: any): Observable
scan(accumulator: function, seed: any): Observable
Reduce해나갑니다.
💡 scan을 활용하여 Redux스러운 상태관리를 할 수 있습니다!
예시
예시 1: 더해나갑니다.
( StackBlitz )
// 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: 객체에서 사용하기
( StackBlitz | jsBin | jsFiddle )
// 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: 누적된 배열에서 무작위 값을 내보냅니다.
( StackBlitz )
// 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 응답을 누적시킵니다
( StackBlitz )
// 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);
관련된 사용법
추가 자료
scan 📰 - 공식 문서
Aggregating streams with reduce and scan using RxJS 📹 - Ben Lesh
Updating data with scan 📹 💵 - John Linquist
Transformation operator: scan 📹 💵 - André Staltz
Build your own scan operator 📹 - Kwinten Pisman
📂 Source Code: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/scan.ts
Last updated
Was this helpful?