
ZIP & ForkJOIN - RXJS Operator
In this tutorial, we will learn about ZIP and Forkjoin of RXJS.
ZIP function
Zip Combines mulitple Observables emitted values with same index. Return 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
forkJoin accepts a variable number of observables and subscribes to them in parallel. When all of the provided observables 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 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");
});