Learn RxJS
Search…
zip

signature: zip(observables: *): Observable

After all observables emit, emit values as an array

πŸ’‘ Combined with interval or timer, zip can be used to time output from another source!
​​
​
​

Examples

Example 1: zip multiple observables emitting at alternate intervals
1
// RxJS v6+
2
import { delay } from 'rxjs/operators';
3
import { of, zip } from 'rxjs';
4
​
5
const sourceOne = of('Hello');
6
const sourceTwo = of('World!');
7
const sourceThree = of('Goodbye');
8
const sourceFour = of('World!');
9
//wait until all observables have emitted a value then emit all as an array
10
const example = zip(
11
sourceOne,
12
sourceTwo.pipe(delay(1000)),
13
sourceThree.pipe(delay(2000)),
14
sourceFour.pipe(delay(3000))
15
);
16
//output: ["Hello", "World!", "Goodbye", "World!"]
17
const subscribe = example.subscribe(val => console.log(val));
Copied!
Example 2: zip when 1 observable completes
1
// RxJS v6+
2
import { take } from 'rxjs/operators';
3
import { interval, zip } from 'rxjs';
4
​
5
//emit every 1s
6
const source = interval(1000);
7
//when one observable completes no more values will be emitted
8
const example = zip(source, source.pipe(take(2)));
9
//output: [0,0]...[1,1]
10
const subscribe = example.subscribe(val => console.log(val));
Copied!
Example 3: get X/Y coordinates of drag start/finish (mouse down/up)
1
// RxJS v6+
2
import { fromEvent, zip } from 'rxjs';
3
import { map } from 'rxjs/operators';
4
​
5
const documentEvent = eventName =>
6
fromEvent(document, eventName).pipe(
7
map((e: MouseEvent) => ({ x: e.clientX, y: e.clientY }))
8
);
9
​
10
zip(documentEvent('mousedown'), documentEvent('mouseup')).subscribe(e =>
11
console.log(JSON.stringify(e))
12
);
Copied!
Example 4: mouse click duration
1
// RxJS v6+
2
import { fromEvent, zip } from 'rxjs';
3
import { map } from 'rxjs/operators';
4
​
5
const eventTime = eventName =>
6
fromEvent(document, eventName).pipe(map(() => new Date()));
7
​
8
const mouseClickDuration = zip(
9
eventTime('mousedown'),
10
eventTime('mouseup')
11
).pipe(map(([start, end]) => Math.abs(start.getTime() - end.getTime())));
12
​
13
mouseClickDuration.subscribe(console.log);
Copied!

Additional Resources

Last modified 9mo ago