All you need to know about combineLatest operator in RxJS

Combines multiple Observable to create an Observable whose values are calculated from the latest values of each of its input Observables.Whenever any input observable emits a value, it computes a formula using the latest values from all the inputs, then emits the output of that formula.

combineLatest combines the values from all the Observables passed as arguments. This happens by subscribing to each Observable in order and, whenever any Observable emits, collecting an array of the most recent values from each Observable. So if we pass an observable to the combineLatest operator, the returned Observable will always emit an array of ‘n’ values, in order corresponding to order of passed Observables (value from the first Observable on the first place and so on).

  • Passing an empty array will result in an Observable that completes immediately.
  • If an error emitted from one observable, the combineLatest throws an error and completes.
  • Emits values, if at least one input observable emits.

A simple code snippet implementing the combineLatest operator is given below.

const ob1$ = interval( 1000 ).pipe(take( 4 ));const ob2$ = of( 5 , 6 , 7 , 8 );const ob3$ = timer( 1000 , 1000 ).pipe(take( 4 ));combineLatest(ob1$, ob2$, ob3$).subscribe(val => console.log(val));

Here we take 3 different source observables and use the combineLatest operator to combine them all and finally we are printing the result.The result for the above code is given below.

// [0, 8, 0]// [1, 8, 0]// [1, 8, 1]// [2, 8, 1]// [2, 8, 2]// [3, 8, 2]// [3, 8, 3]

This is all you need to know about the combineLatest operator to get started.

Software Developer | Author.