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.

Topics covered:

Found this article helpful?

TutsCoder tutorials are free and ad-light — supported by readers like you. Buy me a coffee (or two ☕☕) as a token of appreciation and help keep Angular & Node.js content coming!

One-time. No subscription. 100% optional. 🙏 Every coffee counts!

Leave a Comment

Your email will not be published. Spam-free zone. ✌️

Available for Projects

Need Help With Your
Angular or Node.js Project?

7+ years of MEAN Stack experience. I build scalable Angular 21 apps, Node.js APIs, and SaaS products — delivered on time, every time.

7+ Years MEAN Stack Angular 21 + Nx Expert 20+ Projects Delivered Remote / Freelance