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.
💡 Combined with interval or timer, zip can be used to time output from another source!
const sourceOne = Rx.Observable.of('Hello');
const sourceTwo = Rx.Observable.of('World!');
const sourceThree = Rx.Observable.of('Goodbye');
const sourceFour = Rx.Observable.of('World!');
//wait until all observables have emitted a value then emit all as an array
const example = Rx.Observable
.zip(
sourceOne,
sourceTwo.delay(1000),
sourceThree.delay(2000),
sourceFour.delay(3000)
);
//output: ["Hello", "World!", "Goodbye", "World!"]
const subscribe = example.subscribe(val => console.log(val));
//emit every 1s
const interval = Rx.Observable.interval(1000);
//when one observable completes no more values will be emitted
const example = Rx.Observable
.zip(
interval,
interval.take(2)
);
//output: [0,0]...[1,1]
const subscribe = example.subscribe(val => console.log(val));
- zip 📰 - Official docs
- Combination operator: zip 📹 💵 - André Staltz
📁 Source Code: https://github.com/ReactiveX/rxjs/blob/master/src/operator/zip.ts