What is CombineLatest operator- RXJS
In this tutorial, we will learn about combineLatest and withLatestFrom functions of RXJS.
CombineLatest function
The CombineLatest function combines multiple observables to create an observable, those values are calculated from the latest values of each of its input observables, once any of them emit irrespective of their index.
Suppose we have two dropdown name and color and we want to perform any operation once both of them get selected once, let see how we can do this using combinelatest function
const nameObs = fromEvent<any>(this.name.nativeElement, "change").pipe(
map((event) => event.target.value)
);
const colorObs = fromEvent<any>(this.color.nativeElement, "change").pipe(
map((event) => event.target.value)
);
combineLatest(nameObs, colorObs).subscribe(([name, color]) => {
console.log(name, color);
});
The above example will only run when both of the dropdowns will get value and after that, any of both values changes it will subscribed
withLatestFrom function
The withlatestFrom function combine the source observable with other observables to create a result observable. Those values are calculated from the latest values of each, only when the source emits so source emission is the trigger.
withLatestFrom works as a master and slave, so it will only run when master observable changed.
Example:
const nameObs = fromEvent<any>(this.name.nativeElement, "change").pipe(
map((event) => event.target.value)
);
const colorObs = fromEvent<any>(this.color.nativeElement, "change").pipe(
map((event) => event.target.value)
);
nameObs.pipe(withLatestFrom(colorObs)).subscribe(([name, color]) => {
console.log(name, color);
});
In Above example, it will only run when name dropdown changed.