joachim_b
joachim_b

Reputation: 213

rxjs combineLatest not working as expected

I am struggling with the 'combineLatest' operator... I have a operator chain like so:

    const observable = interval(1000).pipe(
  map((x) => 'myAction'),
  mergeMap((action)=>
    combineLatest([from([1,2,3]),of(action)])
  ),
  tap(result=>{
    console.log('-');
    console.log(JSON.stringify(result));
  })
);

I would expect this output:

[1, 'myAction']
[2, 'myAction']
[3, 'myAction']

what i get is just one output:

[3, 'myAction']

How can I achieve to get the expected result?

Upvotes: 0

Views: 860

Answers (1)

Mrk Sef
Mrk Sef

Reputation: 8062

As the name suggests, combine latest only combines the most recent emissions for the given streams. Since from([1,2,3]) is synchronous, (effectively emits all its values at once), you can get some hard to predict behavior. I haven't tested this, but you may be able to switch the order of the observable and it might work as expected (since of(action) gets subscribed to first).

How I would solve this case:

Since of(action) is just wrapping a single value, I wouldn't bother. Just map the value into your observable directly. That might look like this:

const observable = interval(1000).pipe(
  map(x => 'myAction'),
  mergeMap(action => of(1,2,3).pipe(
    map(n => [n, action])
  )),
  tap(result=>{
    console.log('-');
    console.log(JSON.stringify(result));
  })
);

Upvotes: 1

Related Questions