Skip to content

Instantly share code, notes, and snippets.

@jdpigeon
Created August 13, 2018 19:01
Show Gist options
  • Save jdpigeon/7d0e5dfb706470a09f415ea2f5e4b8f5 to your computer and use it in GitHub Desktop.
Save jdpigeon/7d0e5dfb706470a09f415ea2f5e4b8f5 to your computer and use it in GitHub Desktop.
RxJS withLatestFrom Operator seed
// One of the main 'gotchas' of combination operators like combineLatest and withLatestFrom is that they won't emit until all source observables emit at least once.
// In order to make your combination observables start immediately when they're subscribed to, use the startWith operator on each inner observable
const Rx = require("rxjs");
// emit every 5s
const source = Rx.Observable.interval(5000).startWith('begin');
// emit every 1s
const secondSource = Rx.Observable.interval(1000);
// withLatestFrom slower than source
const example = secondSource.pipe(
// both sources must emit at least 1 value (5s) before emitting
Rx.operators.withLatestFrom(source),
Rx.operators.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));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment