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.
>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.