What is ZIP & ForkJOIN Operator - RXJS

What is ZIP & ForkJOIN Operator - RXJS

In this tutorial, we will learn about ZIP and Forkjoin operator of RXJS.

ZIP function

The Zip operator Combines multiple Observables emitted values with the same index and returns an array of respective values.

Syntax:

zip (observable1, [ observable2, observable3,..., resultSelector])

Zip waits until all the params observables emit values with same index number and only then emits array of these values.

Example:

import { zip, of } from 'rxjs';
import { map } from 'rxjs/operators';
 
let age$ = of(22, 24, 28);
let user$ = of('smith', 'John', 'Cook');
let isActive$ = of(false, true, false);
 
zip(age$, user$, isActive$).pipe(
  map(([age, user, isActive]) => ({ age, user, isActive })),
)
.subscribe(x => console.log(x));
 
// outputs
// { age: 22, user: 'Smith', isActive: false}
// { age: 24, user: 'John', isActive: true }
// { age: 28, user: 'Cook', isActive: false }

As per the above example, each time of the argument observables emit values with same index result observable produces an array of these values.

ForkJoin function

The forkJoin accepts a variable number of observables and subscribes to them in parallel. When all of the provided observables are complete, forkJoin collects the last emitted value from each and emits them as an array (this is by default, more on this later).

When all observables are complete, emit the last emitted value from each

 users = ["jigar", "Maya", "Seema", "Aman"];
 colors = ["red", "blue", "green", "purple"];

 @ViewChild("name", { static: false }) name: ElementRef;
 @ViewChild("color", { static: false }) color: ElementRef;

//Observables
 const nameObs = fromEvent<any>(this.name.nativeElement, "change").pipe(
    map((event) => event.target.value),
    take(4)
 );

 const colorObs = fromEvent<any>(this.color.nativeElement, "change").pipe(
     map((event) => event.target.value),
     take(3)
  );

forkJoin(nameObs, colorObs).subscribe(([name, color]) => {
      console.log(name, color);
      this.createBox(name, color, "ele2");
    });

Subscribe to our Newsletter

Stay up to date! Get all the latest posts delivered straight to your inbox.

If You Appreciate What We Do Here On TutsCoder, You Should Consider:

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

You might also like

Leave a Comment