Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading