Rx-Js Examples

Counter

$(function() {
  function always(x) { return function(_) { return x }}

  var incr = $('#incr').toObservable('click').Select(always(1))
  var decr = $('#decr').toObservable('click').Select(always(-1))

  incr.Merge(decr)
    .Scan(0, function(total, x) { return total + x })
    .Subscribe(updateCount)

  function updateCount(total) {
    $('#count').html(total)
  }
})

Use buttons below to control a simple numeric counter.

This is how it works:

- JQuery is used to get a reference to the #incr button
- rx-jQuery is used to get the stream of button clicks
- The Select combinator is used to map each of these clicks to either 1 or -1. (Haskell list analogy: map)
- The Merge combinator is used to merge the streams of 1's and -1's into a single stream (Haskell list analogy: ++)
- The Scan combinator is used to create a stream of "sum so far". (Haskell list analogy: scanl)
- The Subscribe method is used to attach a side-effect to the stream. The updateCount function just updates the contents of the "total" element