Learn RxJS
Search…
withLatestFrom

signature: withLatestFrom(other: Observable, project: Function): Observable

Also provide the last value from another observable.

πŸ’‘ If you want the last emission any time a variable number of observables emits, try combinelatest!
​​
​
​

Examples

Example 1: Latest value from quicker second source
1
// RxJS v6+
2
import { withLatestFrom, map } from 'rxjs/operators';
3
import { interval } from 'rxjs';
4
​
5
//emit every 5s
6
const source = interval(5000);
7
//emit every 1s
8
const secondSource = interval(1000);
9
const example = source.pipe(
10
withLatestFrom(secondSource),
11
map(([first, second]) => {
12
return `First Source (5s): ${first} Second Source (1s): ${second}`;
13
})
14
);
15
/*
16
"First Source (5s): 0 Second Source (1s): 4"
17
"First Source (5s): 1 Second Source (1s): 9"
18
"First Source (5s): 2 Second Source (1s): 14"
19
...
20
*/
21
const subscribe = example.subscribe(val => console.log(val));
Copied!
Example 2: Slower second source
1
// RxJS v6+
2
import { withLatestFrom, map } from 'rxjs/operators';
3
import { interval } from 'rxjs';
4
​
5
//emit every 5s
6
const source = interval(5000);
7
//emit every 1s
8
const secondSource = interval(1000);
9
//withLatestFrom slower than source
10
const example = secondSource.pipe(
11
//both sources must emit at least 1 value (5s) before emitting
12
withLatestFrom(source),
13
map(([first, second]) => {
14
return `Source (1s): ${first} Latest From (5s): ${second}`;
15
})
16
);
17
/*
18
"Source (1s): 4 Latest From (5s): 0"
19
"Source (1s): 5 Latest From (5s): 0"
20
"Source (1s): 6 Latest From (5s): 0"
21
...
22
*/
23
const subscribe = example.subscribe(val => console.log(val));
Copied!

Additional Resources

Last modified 1yr ago