zip

signature: zip(observables: *): Observable

Description

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!


zip - 图2

Examples

Example 1: zip multiple observables emitting at alternate intervals

( StackBlitz |
jsBin |
jsFiddle )

  1. import { delay } from 'rxjs/operators';
  2. import { of } from 'rxjs/observable/of';
  3. import { zip } from 'rxjs/observable/zip';
  4. const sourceOne = of('Hello');
  5. const sourceTwo = of('World!');
  6. const sourceThree = of('Goodbye');
  7. const sourceFour = of('World!');
  8. //wait until all observables have emitted a value then emit all as an array
  9. const example = zip(
  10. sourceOne,
  11. sourceTwo.pipe(delay(1000)),
  12. sourceThree.pipe(delay(2000)),
  13. sourceFour.pipe(delay(3000))
  14. );
  15. //output: ["Hello", "World!", "Goodbye", "World!"]
  16. const subscribe = example.subscribe(val => console.log(val));
Example 2: zip when 1 observable completes

( StackBlitz |
jsBin |
jsFiddle )

  1. import { take } from 'rxjs/operators';
  2. import { interval } from 'rxjs/observable/interval';
  3. import { zip } from 'rxjs/observable/zip';
  4. //emit every 1s
  5. const source = interval(1000);
  6. //when one observable completes no more values will be emitted
  7. const example = zip(source, source.pipe(take(2)));
  8. //output: [0,0]...[1,1]
  9. const subscribe = example.subscribe(val => console.log(val));

Additional Resources


:file_folder: Source Code:
https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/zip.ts