RxJS: Combining streams: zip operator

Wojciech Trawiński
Sep 4, 2018 · 2 min read

Description

Combining streams in RxJS can be a little bit tricky. You need to know when the resulting stream emits a new value, errors and completes. The combined observable behaviour may be different depending on which RxJS operator is used.

Goal

This is the first post of the series focused on combining streams. The main aim is to get familiar with the operators belonging to the group and get to know when a given observer’s method is called.


Zip in action

Let’s start with an example in which you have two stream of data.

A helper getNewsStream function returns an observable emitting a given number of values, identified by a channel name, with a provided frequency.

You have two streams:

  • sportsNews$: 5 values with 5 second frequency,
  • angularNews$: 3 values with 1 second frequency.

The resulting news$ stream emits an array of values from the inner observables (sportsNews$ and angularNews$). It emits a pair of values.

The flow of data is as follows:

  • 1s passed: angular$(A), sports$(-), news$(-),
  • 2s passed: angular$(AA), sports$(-), news$(-),
  • 3s passed: angular$(AAA|), sports$(-), news$(-),
  • 5s passed: angular$(AAA|), sports$(S), news$(AS),
  • 10s passed: angular$(AAA|), sports$(SS), news$(AS, AS),
  • 15s passed: angular$(AAA|), sports$(SSS), news$(AS, AS, AS|).

where A and S are values emitted by angular and sports streams, respectively.

As you can see, the resulting (zipped) stream won’t emit a value unless there is a corresponding value in each inner observables. In addition, if any of the inner streams has completed and all its values has been picked by the resulting observable, the zipped stream completes. As a result, sports news which don’t have corresponding angular notifications won’t be emitted by the news$ observable.

Live example: https://jsfiddle.net/pfx2evr6/14/


When inner stream errors

Let’s see what happens if any of the inner observables errors.

In the above example, an error is thrown when the second value is emitted by the sportsNews$ observable. The zipped stream (news$) will call the observer’s error callback and won’t emit any successive values if any of its inner observables throws an error. As a result, you will receive only one notification followed by the error message.

Live example: https://jsfiddle.net/pfx2evr6/21/


Like, love, hate, clap!

JavaScript everyday

Wojciech Trawiński

Written by

Doing awesome things using JavaScript

JavaScript everyday

Improve your JavaScript skills everyday!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade