Merge Multiple Observables using combineLatest Operator in RxJS

By Digamber Rawat Last updated on

combineLatest Operator RxJS

I am going to talk about combineLatest operator in RxJS or ReactiveX. I will be telling you what is combineLatest operator then show you how to connect the multiple data streams by using the simplest and easiest way possible. At the end of this article, you’ll be able to understand what combineLatest operator is and how to use this powerful operator in functional reactive programming.

Let’s understand first what this method is…

In RxJS combineLatest operator is used to merge multiple data streams (Observables).

Combinelatest operator joins multiple observable to create an observable. This newly formed observable takes the latest value of every connected observable and emits the latest result.

Graphical Representation

combineLatest operator graphic diaphragm

Let’s Checkout Some Examples Below

Combining 3 observables and getting the latest value using this operator

// RxJS
import { of, combineLatest } from 'rxjs'; 

// 1. Define multiple observables
let color = of('Black', 'Red', 'Blue');
let brand = of('Jaguar', 'Ford', 'BMW');
let price = of(100, 200, 300);

// 2. Call combineLatest operator, inject multiple observables in array
const joinStream = combineLatest(color, brand, price);

// 3. Subscibe combineLatest observable
const subscribe = joinStream.subscribe(([color, brand, price]) => {
  console.log(color + ' ' + brand + ' ' + 'costed me' + ' ' + price );

How to merge two data streams using combineLatest operator?

// RxJS
import { timer, combineLatest } from 'rxjs';

// 1. Define 2 data stream (observables), using timer which emits value in every 2 second
const firstTimer = timer(1000, 2000);
const secondTimer = timer(3000, 2000);

// 2. Call combineLatest operator, inject data stream observables in an array
const connectStream = combineLatest(firstTimer, secondTimer);

// 3. Subscibe combineLatest
const subscribe = connectStream.subscribe(([firstTimer, secondTimer]) => {
  console.log('First Timer' + ' ' + firstTimer);
  console.log('First Timer' + ' ' + secondTimer);

Official Document

Find official RxJS combineLatest document here

If you are new to RxJS or ReactiveX then I would suggest follow this tutorial to understand the basic concept of RxJS.

Digamber Rawat
Digamber Rawat

Full stack developer with a passion for UI/UX design. I create beautiful and useful digital products to solve people’s problem and make their life easy.

Hire Me