61

I want to merge the latest emitted values from multiple Observables, so right now I'm using .withLatestFrom. Except, it nests the data together in nested arrays instead of pushing the data into a new array value. Example code below.

Any ideas on how I can retrieve multiple Observable emits using .withLatestFrom?

source0
  .withLatestFrom(source1)
  .withLatestFrom(source2)
  .withLatestFrom(source3)
  .map((data) => { console.log(data) });
BinaryButterfly
  • 18,137
  • 13
  • 50
  • 91
Preda70R
  • 958
  • 1
  • 9
  • 10

2 Answers2

128

withLatestFrom supports multiple observables:

.withLatestFrom(source1, source2, source3)
.map((data) => { console.log(data) });

-> [val, value1, value2, value3]

It also supports function as it's last parameter, so you can get values other than arrays:

observable$
    .withLatestFrom(source1, source2, (val, one, two) => {
        return {val: val, one: one, two: two};
     });
adharris
  • 3,591
  • 1
  • 21
  • 18
  • 7
    You can wrap the `{}` with `()` then you don't need an explicit return statement : `.withLatestFrom(source1, source2, (val, one, two) => ({ val: val, one: one, two: two }));` – Simon_Weaver Jun 21 '17 at 19:05
9

withLatestFrom accepts multiple observables. so you can write it like:

let obs1$ = Rx.Observable.of('a');
let obs2$ = Rx.Observable.of('b');

Rx.Observable.interval(1000)
  .withLatestFrom(obs1$, obs2$)
  .subscribe(x=>console.log(x))
Julia Passynkova
  • 17,256
  • 6
  • 33
  • 32