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

How to get the last value from all Observables when any of them emit a new value?

I have N Observables/BehaviourSubjects, binded to N select fields. Wich is the best approach using RxJS to get the last value from all observables when one of them emit a new value ?

I’m developing a filter, so when one filter changes, i’ll need to call backend with all filters selected on the screen.

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

>Solution :

The best approach is to use a combineLatest when you need a value from two or more reactive structures. It is an operator that combines two or more observables and generates values for all of them every time one of the observables generates a value. Here is an example from the RxJs documentation:

const timerOne$ = timer(1000, 4000);
const timerTwo$ = timer(2000, 4000);
const timerThree$ = timer(3000, 4000);

combineLatest([timerOne$, timerTwo$, timerThree$])
   .subscribe(([timerValOne, timerValTwo, timerValThree]) => {
      console.log(
      `Timer One Latest: ${timerValOne},
      Timer Two Latest: ${timerValTwo},
      Timer Three Latest: ${timerValThree}`
    );
  }
);

And here is a working example: https://playcode.io/1046311

Hope I helped you! See https://www.learnrxjs.io/learn-rxjs/operators/combination/combinelatest for more information.

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