Sharing a Cold Observable

Learn how more than one subscriber is dealt with and the usage of the bufferWithTime operator.

We'll cover the following

Let’s get back to the example of earthquakes. The code we have so far looks reasonable. We have a quakes Observable with two subscriptions: one that paints the earthquakes on the map, and another that lists them in the table.

However, we can make our code much more efficient. By having two subscribers to quakes, we are, in fact, requesting the data twice. We can check that by putting a console.log inside the flatMap operator in quakes.

This happens because quakes is a cold Observable, and it will re-emit all its values to each new subscriber. Therefore, a new subscription means a new JSONP request. Our application performance is affected if we request the same resources twice over the same network.

For the next example, we’ll use the share operator, which automatically creates a subscription to the Observable when the number of Observers goes from zero to one.

This spares us from calling the connect function:

Get hands-on with 1200+ tech skills courses.