signature: zip(observables: *): Observable


TL;DR: After all observables emit, emit values as an array

The zip operator will subscribe to all inner observables, waiting for each to emit a value. Once this occurs, all values with the corresponding index will be emitted. This will continue until at least one inner observable completes.

:bulb: Combined with interval or timer, zip can be used to time output from another source!


Example 1: zip multiple observables emitting at alternate intervals

( StackBlitz | jsBin | jsFiddle )

import { delay } from 'rxjs/operators';
import { of } from 'rxjs/observable/of';
import { zip } from 'rxjs/observable/zip';

const sourceOne = of('Hello');
const sourceTwo = of('World!');
const sourceThree = of('Goodbye');
const sourceFour = of('World!');
//wait until all observables have emitted a value then emit all as an array
const example = zip(
//output: ["Hello", "World!", "Goodbye", "World!"]
const subscribe = example.subscribe(val => console.log(val));
Example 2: zip when 1 observable completes

( StackBlitz | jsBin | jsFiddle )

import { take } from 'rxjs/operators';
import { interval } from 'rxjs/observable/interval';
import { zip } from 'rxjs/observable/zip';

//emit every 1s
const source = interval(1000);
//when one observable completes no more values will be emitted
const example = zip(source, source.pipe(take(2)));
//output: [0,0]...[1,1]
const subscribe = example.subscribe(val => console.log(val));

Additional Resources

:file_folder: Source Code:

results matching ""

    No results matching ""