π‘ If you want the last emission any time a variable number of observables emits, try combinelatest!
ββββ
Example 1: Latest value from quicker second source
( StackBlitz | jsBin | jsFiddle )
// RxJS v6+import { withLatestFrom, map } from 'rxjs/operators';import { interval } from 'rxjs';β//emit every 5sconst source = interval(5000);//emit every 1sconst secondSource = interval(1000);const example = source.pipe(withLatestFrom(secondSource),map(([first, second]) => {return `First Source (5s): ${first} Second Source (1s): ${second}`;}));/*"First Source (5s): 0 Second Source (1s): 4""First Source (5s): 1 Second Source (1s): 9""First Source (5s): 2 Second Source (1s): 14"...*/const subscribe = example.subscribe(val => console.log(val));
Example 2: Slower second source
( StackBlitz | jsBin | jsFiddle )
// RxJS v6+import { withLatestFrom, map } from 'rxjs/operators';import { interval } from 'rxjs';β//emit every 5sconst source = interval(5000);//emit every 1sconst secondSource = interval(1000);//withLatestFrom slower than sourceconst example = secondSource.pipe(//both sources must emit at least 1 value (5s) before emittingwithLatestFrom(source),map(([first, second]) => {return `Source (1s): ${first} Latest From (5s): ${second}`;}));/*"Source (1s): 4 Latest From (5s): 0""Source (1s): 5 Latest From (5s): 0""Source (1s): 6 Latest From (5s): 0"...*/const subscribe = example.subscribe(val => console.log(val));
βProgress Barβ
βGame Loopβ
βSpace Invaders Gameβ
βUncover Image Gameβ
βwithLatestFrom π° - Official
docs
βwithLatestFrom - In Depth Dev Reference
βCombination operator: withLatestFromβ
π₯ π΅ - AndrΓ© Staltz
π Source Code: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/withLatestFrom.tsβ