Search code examples
javascripttypescriptrxjsrxjs-pipeable-operatorsrxjs-observables

Why operators (tap, map) are not called on inner observable, when using combineLatest?


Why are operators tap and map of inner observable not called? combineLatest should subscribe to observables it gets in obsArr, right? Why this subscription does not trigger those operators?

const obsArr = [];

[[1, 2], [3, 4], [5, 6]].map(arr => {

  const observable = from(arr);

  observable.pipe(
    tap(item => {
      // this is NOT called
      console.log('tap', item)
    }),
    map(item => {
      // this is NOT called
      return item * -1;
    })
  );

  obsArr.push(observable);
});

combineLatest(obsArr).subscribe(latestValues => {
  console.log(latestValues);
  // LOG: [2, 4, 5]
  // LOG: [2, 4, 6]
});

Working stackblitz: https://rxjs-y2h4rn.stackblitz.io

Thanks for explanation!


Solution

  • The problem is that you are adding pipe to the observable, but pushing the original Observable to the array. Instead you should push the modified observable:

    [[1, 2], [3, 4], [5, 6]].map(arr => {
    
      const observable = from(arr);
    
      obsArr.push(observable.pipe(
        tap(item => {
          console.log('tap', item)
        }),
        map(item => {
          return item * -1;
        })
      ));
    });