CombineLatest - RXJS Operator

CombineLatest - RXJS Operator

In this tutorial, we will learn about combineLatest and withLatestFrom function of RXJS.

CombineLatest function

CombineLatest 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

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

Subscribe to our Newsletter

Stay up to date! Get all the latest posts delivered straight to your inbox.

If You Appreciate What We Do Here On TutsCoder, You Should Consider:

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

You might also like