Angular + RxJS - combineLatestWith
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));
[ "Mahesh", "Krishn" ]
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")) ); }
{{result$ | async | json}}
[ [ "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)); }
Ganga-Yamuna-Saraswati
4. Complete Example
emp.component.tsimport { 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)); } }
{{result$ | async | json}}
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' }); } }