π‘ You can create Redux-like state management with scan!
ββββ
Example 1: Sum over time
( StackBlitz )
// RxJS v6+import { of } from 'rxjs';import { scan } from 'rxjs/operators';βconst source = of(1, 2, 3);// basic scan example, sum over time starting with zeroconst example = source.pipe(scan((acc, curr) => acc + curr, 0));// log accumulated values// output: 1,3,6const subscribe = example.subscribe(val => console.log(val));
Example 2: Accumulating an object
( StackBlitz | jsBin | jsFiddle )
// RxJS v6+import { Subject } from 'rxjs';import { scan } from 'rxjs/operators';βconst subject = new Subject();//scan example building an object over timeconst example = subject.pipe(scan((acc, curr) => Object.assign({}, acc, curr), {}));//log accumulated valuesconst subscribe = example.subscribe(val =>console.log('Accumulated object:', val));//next values into subject, adding properties to object// {name: 'Joe'}subject.next({ name: 'Joe' });// {name: 'Joe', age: 30}subject.next({ age: 30 });// {name: 'Joe', age: 30, favoriteLanguage: 'JavaScript'}subject.next({ favoriteLanguage: 'JavaScript' });
Example 3: Emitting random values from the accumulated array.
( StackBlitz )
// RxJS v6+import { interval } from 'rxjs';import { scan, map, distinctUntilChanged } from 'rxjs/operators';β// Accumulate values in an array, emit random values from this array.const scanObs = interval(1000).pipe(scan((a, c) => [...a, c], []),map(r => r[Math.floor(Math.random() * r.length)]),distinctUntilChanged()).subscribe(console.log);
Example 4: Accumulating http responses over time
( StackBlitz )
// RxJS v6+import { interval, of } from 'rxjs';import { scan, delay, repeat, mergeMap } from 'rxjs/operators';βconst fakeRequest = of('response').pipe(delay(2000));β// output:// ['response'],// ['response','response'],// ['response','response','response'],// etc...βinterval(1000).pipe(mergeMap(_ => fakeRequest),scan < string > ((all, current) => [...all, current], [])).subscribe(console.log);
β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 π° - Official docs
β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β