Reactive Programming With JavaScript

Suraj KC
YoungInnovations' Blog
4 min readDec 28, 2016

--

Reactive programming is a programming pattern that focuses on :

  • asynchronous programming
  • observable data streams

Asynchronous programming allows writing non blocking code. Many of us are familiar to asynchronous programming in the form of jQuery promises with AJAX. NodeJS has become hugely popular due to its asynchronous programming style. And reactive programming combines methods we are already familiar and concepts of functional programming techniques to give new approach to asynchronous programming.

So, what are observable data streams ? Well, stream is just a sequence of events. Data stream can comprise of UI events, array elements and the most popular, that we are going to use a lot is stream of http requests. Sure, there can be other type of streams. In reactive programming, an observer subscribes to an observable. An observer is an an object who gets notified when the data stream changes, or gets updated. An observable emits multiple values over time or sends notification to its observers by calling the observers’ methods.

So, the important question can be: why use reactive programming and observable? And honestly I am trying to figure out this make sense of this pattern over other patterns/options available and would love to hear your take on this. Observable is a big part of ES7 and we can use it today using RxJS library for reactive programming. This library can also be used with other languages such as C#, Java ruby etc.

Enough with the theory, lets get to the coding:

You can install Rxjs Library from npm repository to set up on your device.

npm install rxjs

To import RxJS functionality:

import Rx from ‘rxjs/Rx’;

To learn more about installation, visit this link.

You can try experimenting with RxJS in this codepen.

var source = Rx.Observable.fromEvent(document.body, 'mousemove');source.subscribe(val => console.log(val),
e => console.log(e),
() => console.log('completed'));
source.subscribe(val => {
console.log(`x: ${val.offsetX} & y: ${val.offsetY}`)
},
e => console.log(e),
() => console.log('completed'));

We can create observable of sequence of mousemove events and observer listening to changes of that observer can react to the event.

Observable can be simply looked as an array, but it can be populated over time with new values asynchronously. And we also can use map, filter,reduce and other operators with observables just like arrays.

var numbers = [1,4,5,6];

Here, numbers is simply an array. Lets convert it to an observable. We can use from() to turn an array, promise or iterable to an observable.

var source = Rx.Observable.from(numbers);

We have declared an observable, and it is like declaring a function, it does nothing until invoked. Invoking observable is called subscribing the the observable.

source.subscribe(val => console.log(val),  //next methode => console.log(err),   //error method() => console.log('complete'));  //complete method//Output
//1
//4
//5
//6

If we want to listen to the data or find what is inside, we subscribe to the observable using observer. Observer needs three methods:

Well this source observable can receive stream of data asynchronously and we can use observer to listen to the changes and react to it.

And like arrays, we can use map(), filter(), reduce() etc on the observable. These methods are called operators and return new observable form source observable.

var numbers = [1,4,5,6];
var source = Rx.Observable.from(numbers)
.map(val => val*2)
.filter(val => val > 2);
source.subscribe(val => console.log(val),
e => console.log(e),
() => console.log('complete'));
//Output
//8
//10
//12
//complete

Well, we can use low level create() to implement our own observable. It creates a new observable with logic in the subscribe function. In most cases, we need not use this method as the library provides operators to satisfy most use cases. However, its good to know there exists low level method to create our own observable.

var msg = Rx.Observable.create(function(observer){
observer.next(‘Hello’);
observer.next(‘World’)
})
msg.subscribe(val => console.log(val))//Output
//Hello
//World

Lets make our previous observable array asynchronous with setTimeout() so that our observer can listen to changes in the observable and react to it and do some logic.

var numbers = [1,4,5,6];
var source = Rx.Observable.create(observer => {

var num = 0;
var generateVal = () => {
observer.next(numbers[num++]);

if(num < numbers.length){
setTimeout(generateVal,2000);
}

}

generateVal();

})
source.subscribe(val => console.log(val),
e => console.log(e),
() => console.log('complete'));
//Output
//1
//4
//5
//6

Well, observables can be used like promises in our applications. Infact, promise is just a simple observer with single result from asynchronous operation. While observables can emit multiple events and return multiple results to its subscriber.

To give a real world example, which is the method I have used in one of my projects in Angular 2, we can use this library for requesting data from server and render the response in our UI.

var requestUrl =”https://api.github.com/users";var response = Rx.Observable.fromPromise(jQuery.getJSON(requestUrl));response$.subscribe((val) => console.log(val),
(err) => console.log(err),
() => console.log('complete'));

We can convert a simple promise to an observable with fromPromise() and emit result of the promise to the listener. And we have an observer listening to to the response observable. While observable has all the perks of a promise, we can use vast library of operators to carryout complex operations and transform it into new observable.

To look at the bigger picture, we can use observable to watch the behaviors of states or some data or variables and manage the state across the application by reacting to changes in the observable stream. It can be used change detection strategy to update UI based on changes or updates in model without re-rendering the page. Observable is a big part of ES7, the next evolution of JavaScript. And learning observables helps in getting prepared be in forefront when ES7 becomes available and it certainly improves our asynchronous programming skills.

To learn more about reactive programming and RxJS, you can visit this site.

I would love to share more about this on further posts. Stay tuned.

Happy coding :)

--

--