Reactive Extensions for Javascript – Causing side effects with Do

I wrote previously about how you can set up multiple observable sequences and subscribe to them with multiple observers and create a many-to-many relationship between them.

Whilst this is a very flexible model with a clear separation of responsibilities, often it requires more work to set up and is more than what you need for the task at hand. For instance, if you’re receiving a steady stream of inputs and want to log the arrival of new inputs as well as performing some aggregation on them, you don’t necessarily have to create two subscribers for the input but instead make use of the Rx.Observable.Do function.

Like the Rx.Observable.Subscribe function, the Do function can take a subscriber, or two up to three function objects to handle the onNext, onError and onCompleted events, in that order. Unlike the Rx.Observable.Select function, it doesn’t have a return value and therefore won’t allow you to transform the input stream, it’s intended purely for causing side effects.

I’ve put together a quick demo (see below) to illustrate the use of the Do function in conjunction with other common RxJS functions such as Select and Where. For this demo we just need two <span> elements, one to show the running total, the other to show a log message every time a new value is received:

   1: <body>

   2:     <div id="wrapper">

   3:         <p>Sum of squares of odd numbers received : <span id="sum"></span></p>

   4:         <p><span id="log"></span></p>

   5:     </div>

   6: </body>

And the Javascript to go along with it:

   1: <script type="text/javascript" src="js/jquery/jquery-1.4.4.min.js"></script>

   2: <script type="text/javascript" src="js/rxjs/rx.js"></script>

   3:  

   4: <script type="text/javascript">

   5:     $(function () {

   6:         var logSpan = $("#log"), sumSpan = $("#sum");

   7:  

   8:         // create an observable which gives ten numbers in total at 1 second 

   9:         // interval with a 13% chance of exception being thrown at each interval

  10:         var observable = Rx.Observable.GenerateWithTime(

  11:             1,                                  // initial state

  12:             function (x) { return x <= 10; },   // condition

  13:             function (x) {                      // iterator

  14:                 var prob = Math.random();

  15:                 if (prob < 0.13) {

  16:                     throw "Better luck next time!";

  17:                 }

  18:  

  19:                 return x + 1;

  20:             },

  21:             function (x) { return x; },         // select

  22:             function (x) {                      // interval

  23:                 return x === 0 ? 0 : 1000

  24:             });

  25:  

  26:         var sum = 0;

  27:  

  28:         observable.Do(function (n) {    // onNext

  29:             logSpan.html("Received new input: " + n);

  30:         }, function (err) {             // onError

  31:             logSpan.html("Error: " + err);

  32:         }, function () {               // onCompleted

  33:             logSpan.html("No more inputs");

  34:         }).Where(function (n) {         // filter the input sequence

  35:             return n % 2 != 0;          // odd numbers only

  36:         }).Select(function (n) {        // transform the input sequence

  37:             return n * n;

  38:         }).Subscribe(function (n) {

  39:             sum += n;                   // add the new input to the running total

  40:             sumSpan.html(sum);          // show the new running total

  41:         });

  42:     });

  43: </script>

Couple of things to note here:

  • line 13 – this is a deliberate attempt to give the observable sequence a random chance of excepting to invoke the onError handler specified in the Do function on line 30
  • line 28 – the Do function updates the HTML content in the log <span> element every time it receives a new value
  • line 32 – show a different log message when we have exhausted the observable sequence
  • line 34 – apply a filter on the observable sequence for all subsequent functions
  • line 36 – only odd numbers are fed to this handler

Demo

If you are lucky enough (or unlucky enough depending on which scenario you’re trying to test) just refresh the page and try again and hopefully you have better luck the second time around!