Rx JS Demystified

01 Jul 2017

What is Reactive Programming

Reactive programming is a programming paradigm that help us to work on streams of data. The stream could be a series of mouse events , data arriving from a network request or even as simple as an array of integers.

When we talk about data there will always be a sender and a receiver , In reactive programming they are known as a publisher and consumer . Reactive programming deals about moving the data from the publisher to the consumer without having to worry about the details of how its being done. In other words declarative style of programming is used.

Rx programming model was developed in Microsoft and has implementations in many languages which include java,scala , java script . This blog will talk about the javascript implentation Rx Js.

Inspiration

Long long ago when the GOF design patterns was conceptualised , no one ever thought that the observer and the iterator patterns were related to each other as shown be the diagram here

But then after several years people started realising the symmetry between both the patterns.

Both the patterns deal with data . In the observer pattern which we generally associate with events (mouse click , key press etc ) the publisher of the event is in control . The consumer has no control over whether the event will even happen or the amount of data that it will produce.The model is a push model with the publisher pushing data to the consumer

The iterator design pattern commonly used to iterate over collections , the consumer is in control . The consumer invokes the next() method to pull data from the publisher until

When the symmetry was noticed people came up with the idea of Reactive programming where it was able to have a common interface to deal with pushed data (like data coming from events , data from a request over the network , web sockets) and static data like arrays .

The Observable is central to the Rx pattern but instead of the consumer requesting values from the publisher (as in the iterator) the observable pushes values to the observer as soon as it is available . Its like saying “Dont call us , we’ll call you “

Rx Js api

The Rx Js api is available here

Applications

A very basic example of Rx Js used in search

Observables can be created from events , promises or even plain arrays .

Rx.Observable.fromEvent(q, 'keyup') .debounce(() => Rx.Observable.timer(3000)) .map(function (ev) { return ev.target.value; }) .filter(function (text) { return text.length >= 3; }) .distinctUntilChanged() .map(searchFor)

Autocomplete using switchMap

Problems while implementing an autocomplete

switchMap comes to our rescue here . This function ensures that the result matches thelast text typed in by the user.

Rx Js with Promises

An Observable can be created from Promise . It can have multiple subscribers as shown in the example below. Note that ‘Init Observable’ will be called only once despite the observable having multiple subscriber