COLD VS Hot observables

Source: Internet
Author: User
Hot vs Cold observables

Understanding the nature of hot and cold observables are a crucial part to master observables. Before we try to explore the topic through some practical examples, let's read through the definition from the RxJS projec T itself

Cold observables start running upon subscription, i.e., the observable sequence only starts pushing values to the Observer s when the Subscribe is called. (...) This was different from hot observables such as mouse move events or the stock tickers which are already producing values even Before a subscription is active.

Ok, so far so good. Let's see how that's means in practice.

We start with a basic Observable that simply emits the number 1. We make both independent subscriptions to the same Observable and print out the output with a prefix so that we can tell th Em apart.

Let OBS = Rx.Observable.create (Observer = Observer.next (1));

Obs.subscribe (v = console.log ("1st subscriber:" + V));
Obs.subscribe (v = console.log ("2nd subscriber:" + V));

When we run this code we'll see the following output in the console.

1st subscriber:1
2nd subscriber:1

Ok, cool. But is the interesting question Remains:is obs cold or hot? Let's forget for a moment so we know how OBS is created and imagine we would has obtained a reference to OBS by Callin G Getobservablefromsomewhere () instead. If that is the case, we wouldn ' is able to tell whether it's cold or hot. And that's one important thing to understand. It's not always possible from the subscriber side to know whether you is dealing with a cold or hot Observable.

If We turn back to the definition so we cited in the beginning and think about what makes a Observable cold or hot, we Can read between the lines and notice that if OBS is cold it should produce fresh values upon subscription. But the pity are, with a value such as 1 we can ' t easily tell whether it were created freshly upon subscription or not. So let's replace 1 with Date.now () and see what happens.

If we run that code again we'll notice that we actually get different output per subscription. Notice the last digit.

1st subscriber:1465990942935
2nd subscriber:1465990942936

With this output it's clear that there must has been, calls to Observer.next (Date.now ()). In other words, the observablestarted producing the values upon each subscription which makes it cold by definition. Making Cold observables Hot

Now the We know that we Observable are clearly cold, let's try to warm it up a little.

Let Obs = rx.observable
            . Create (Observer = Observer.next (Date.now ()))
            . publish ();

Obs.subscribe (v = console.log ("1st subscriber:" + V));
Obs.subscribe (v = console.log ("2nd subscriber:" + V));

Obs.connect ();

Let's ignore the publish and connect operators for a moment and solely focus on the output.

1st subscriber:1465994477014
2nd subscriber:1465994477014

Clearly we can see that there must has been only one call to Observer.next (Date.now ()) with this setup as the numbers is Identical. So, are it hot now? Well, kind of. Let's put it that Way:it's warmer than a cold one but colder than a really hot one. It's hot in the sense that there ' s no new value producer/source (the thing calling Observer.next (Val)) created upon SUBSCR Iption. But it's cold in the sense that it doesn ' t start producing values before the subscriptions exist.

We can fix this by moving the connect call before the subscriptions.

Let Obs = rx.observable
            . Create (Observer = Observer.next (Date.now ()))
            . publish ();
Obs.connect ();

Obs.subscribe (v = console.log ("1st subscriber:" + V));
Obs.subscribe (v = console.log ("2nd subscriber:" + V));

However, when we run the This code we don ' t see any output at all. And that's expected behaviour because now obs are really really hot as in it produces values no matter if anyone listens or Not. So by the time, we have a subscribers start listening the value has a long been pumped through.

In order to being able to understand the purpose of publish better, let's use a Observable that'll produce infinite values Instead of just a single one.

Let Obs = rx.observable
            . Interval (+).
            publish ()
            . RefCount ();

Obs.subscribe (v = console.log ("1st subscriber:" + V));
SetTimeout (()
  //delay for a little more than a second and then add second subscriber
  = obs.subscribe (v = Console.log ("2nd subscriber:" + V)), 1100);

The setup we use are slightly more complex from what we had before and so let's break it down.

We use interval (+) to the Create an Observable, emits every second with a increasing index value starting at 0.

We use Publish to share the value producer across several subscriptions (one indicator of being hot!)

We defer the second subscription by one second.

Let's just ignore refcount for now as a we ' re going to explain it later.

We see the following output as we run the script.

1st subscriber:0
1st subscriber:1
2nd subscriber:1
1st subscriber:2
2nd subscriber:2
...

Clearly, we can see that the second Subscriber are not starting over at 0. But that would has been the case if we didn ' t usepublish to share the value producing source across subscribers. Understanding Publish, RefCount and connect

But how does hot are obs in this scenario? Let's make it visible by defering both subscriptions by another 2 seconds. If it ' s really hot we shouldn ' t see the numbers 0 and 1 at all because they would has been emitted before we start to Lis Ten, right?

Let's try out and run the this code instead.

Let Obs = rx.observable
            . Interval (+).
            publish ()
            . RefCount ();

SetTimeout (() = {
  //delay both subscriptions by 2 seconds
  obs.subscribe (v = console.log ("1st subscriber: "+ V));
  SetTimeout (
    //delay for a little more than a second and then add Second subscriber
    () = Obs.subscribe (
          V = = Console.log ("2nd subscriber:" + V)), 1100);

},2000);

Interestingly we see exactly the same output as in the previous experiment which means we is dealing with an OBSERVAB Le that's rather warm than really hot. And that ' s because of the way refcount works. The publish operator creates Anconnectableobservable which means it creates an Observable that shares one Single subscription to the underlying source. However, The publish operator doesn ' t subscribe to the underlying source just yet. It's more like a gatekeeper this makes sure that subscriptions aren ' t made to the underlying source and to The connec Tableobservable instead.

It's the job of the Connect operator to actually cause the connectableobservable to subscribe to the underlying source (th E thing that produces values). In our case we ' re using the RefCount which is a operator that builds up on connect and causes Theconnectableobservable to Sub scribe to the underlying source as soon as there are a first subscriber and to unsubscribe from it as soon as there ' s no su Bscriber anymore. It simply keeps track of what many subscriptions is made to the connectableobservable.

And this explains why we see the values starting at 0 with our last experiment. It's because the subscription to the underlying source are only made once so we have a first subscriber to the CONNECTABL Eobservable.

If we want OBS to is truly hot, we had to call connect ourselves early on.

Let Obs = rx.observable
            . Interval (+)
            . publish ();
Obs.connect ();

SetTimeout (() = {
  Obs.subscribe (v = console.log ("1st subscriber:" + V));
  SetTimeout (
    () = Obs.subscribe (v = console.log ("2nd subscriber:" + V)), +),

},2000);

Notice how we get values starting from 2 when we

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.