withLatestFrom

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

Also provide the last value from another observable.


:bulb: If you want the last emission any time a variable number of observables
emits, try combinelatest!


withLatestFrom - 图2

Examples

Example 1: Latest value from quicker second source

( StackBlitz |
jsBin |
jsFiddle )

  1. import { withLatestFrom, map } from 'rxjs/operators';
  2. import { interval } from 'rxjs/observable/interval';
  3. //emit every 5s
  4. const source = interval(5000);
  5. //emit every 1s
  6. const secondSource = interval(1000);
  7. const example = source.pipe(
  8. withLatestFrom(secondSource),
  9. map(([first, second]) => {
  10. return `First Source (5s): ${first} Second Source (1s): ${second}`;
  11. })
  12. );
  13. /*
  14. "First Source (5s): 0 Second Source (1s): 4"
  15. "First Source (5s): 1 Second Source (1s): 9"
  16. "First Source (5s): 2 Second Source (1s): 14"
  17. ...
  18. */
  19. const subscribe = example.subscribe(val => console.log(val));
Example 2: Slower second source

( StackBlitz |
jsBin |
jsFiddle )

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

Additional Resources


:file_folder: Source Code:
https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/withLatestFrom.ts