Search code examples
angularrxjs

Code optimization to remove nested Subscribe in Angular


I have a following scenario inside subscription.add. I dont want nested subscribe. Any Suggestion.I want to check that both Firstvalue and SecondValue data is available to dispatch an action.

this.subscription.add(
  this.store.select(FristState?.firstValue).subscribe(() => {
    this.store.select(SecondState?.secondValue).subscribe((secondValue) => {
      console.log(secondValue)
    });
  })
);

Solution

  • You want to use combineLatest which will emit a value for each new one

    https://www.learnrxjs.io/learn-rxjs/operators/combination/combinelatest

    Your code equivalent from what you posted would be

    this.subscription.add(
      combineLatest([
        this.store.select(FirstState?.firstValue),
        this.store.select(SecondState?.secondValue)
      ]).subscribe(([firstValue, secondValue]) => {
        console.log(secondValue);
      })
    );
    

    Note this will emit for every new value of FirstState and SecondState as your example code did because redux stores are BehaviorSubjects