Angular + RxJS - combineLatestWith

By Arvind Rai, February 01, 2024
On this page, we will learn using RxJS combineLatestWith() operator in our Angular application.
1. combineLatestWith is a RxJS operator that combines latest values from source observable and all passed observables into array.
2. combineLatestWith returns an observable and on subscribe, we will get the values as an array.
3. combineLatestWith is useful operator to eagerly calculate values based on change input.
4. Find the construct of the operator from RxJS doc.
combineLatestWith(...otherSources: [...ObservableInputTuple]): OperatorFunction 

1. Combining Two Observable

Find a sample code here.
of("Mahesh").pipe(
   combineLatestWith(of("Krishn"))
).subscribe(val => console.log(val)); 
Output
[ "Mahesh", "Krishn" ] 
Source observable is combined with another observable. On subscribe, we see that the values of source and another observable is combined in an array.

2. Combining Three or More Observable

Find the code to combine values of source observable + two other observable.
TS :
result$!: Observable<Array<any>>;
ngOnInit() {
   this.result$ = of("101").pipe(
      combineLatestWith(of("Shiv")),
      combineLatestWith(of("Varanasi"))
   );
} 
HTML :
{{result$ | async | json}} 
Output
[ [ "101", "Shiv" ], "Varanasi" ] 

3. Combining Values as String

Find the code to combine values as string.
result$!: Observable<string>;
ngOnInit() {
   this.result$ = of("Ganga").pipe(
      combineLatestWith(of("Yamuna")),
      combineLatestWith(of("Saraswati")),
      map(data => {
         const arr1 = data[0];
         return arr1[0] + "-" + arr1[1] + "-" + data[1] ;
      })
   );
   this.result$.subscribe(res => console.log(res));
} 
Output
Ganga-Yamuna-Saraswati 

4. Complete Example

emp.component.ts
import { Component, OnInit } from '@angular/core';
import { Observable, combineLatestWith } from 'rxjs';
import { EmpService } from './services/emp.service';
import { CommonModule } from '@angular/common';

@Component({
   selector: 'my-app',
   standalone: true,
   imports: [CommonModule],
   templateUrl: './emp.component.html'
})
export class EmpComponent implements OnInit {
   constructor(private empService: EmpService) {
   }
   result$!: Observable<any>;
   ngOnInit() {
      this.result$ = this.empService.getAdmin().pipe(
         combineLatestWith(this.empService.getCompanyDetail())
      );
      this.result$.subscribe(res => console.log(res));
   }
} 
emp.component.html
{{result$ | async | json}} 
emp.service.ts
import { Injectable } from '@angular/core';
import { of } from 'rxjs';

@Injectable({
    providedIn: 'root'
})
export class EmpService {
    getAdmin() {
        return of({ id: 100, name: "Ram" });
    }
    getCompanyDetail() {
        return of({ name: "XYZ", location: 'Varanasi' });
    }
} 

5. Reference

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us