Reactive Extensions for Javascript — Observable vs ConnectableObservable

Yan Cui
theburningmonk.com
Published in
2 min readMar 15, 2011

For those of you who are familiar with Reactive Extensions you should know all about observables already, but did you know that there’s another kind of observable sequence — Rx.ConnectableObservable.

The difference between the two types of observable sequences is well explained here, in short, a connectable observable sequence allows you to share the same source sequence of values with multiple subscribers whilst the normal observable sequence gives each subscriber its own sequence of values. Whilst in most cases this difference doesn’t have any practical impacts as each subscribers are given the same values in the same order, however, consider this observable sequence of random numbers between 0 and 1000:

1: var maxNumber = 1000;2: var observableSource = Rx.Observable.GenerateWithTime(3:     Math.random(),                                      // initial state4:     function (x) { return true; },                      // condition5:     function (x) { return Math.random(); },             // iterator6:     function (x) { return parseInt(x * maxNumber); },   // select7:     function (x) { return 1000 });                      // interval

As you can see, each time the iterator is invoked it’ll generate a different value, hence subscribers will receive a different value each time (see demo below):

1: // first subscriber2: observableSource.Subscribe(function (n) {3:     sub1Span.html(n);4: });5:6: // second subscriber7: observableSource.Subscribe(function (n) {8:     sub2Span.html(n);9: });

Instead, if you want to ensure that all the subscribers receive the same values, your best bet is to ‘publish’ the source:

1: // create a connectable observable from the source2: var connectableObservable = observableSource.Publish();

which returns you a connectable observable that you can then attach subscribers to:

1: // connected subscriber 12: connectableObservable.Subscribe(function (n) {3:     connSub1Span.html(n);4: });5:6: // connected subscriber 27: connectableObservable.Subscribe(function (n) {8:     connSub2Span.html(n);9: });

and once you ‘connect’ to the underlying source, the subscribers will start receiving values from the stream:

1: connectableObservable.Connect();

Demo

--

--

Yan Cui
theburningmonk.com

AWS Serverless Hero. Follow me to learn practical tips and best practices for AWS and Serverless.