Understanding RxJS

RxJS is one of the popular libraries in web development. It offers a functional approach for dealing with events and with integrations with different frameworks, libraries. Its a modern approach for reactive programming.

Reactive programming is just a different way of building a software application. This actually means a software that is build to react on changes such as events, data being fetched etc, instead of the old way of writing a code to handle the changes .

Reactive programming is an API for asynchronous programming with observable streams

RxjS allows us to write software that is reusable, configurable and asynchronous. RxJS really helps when using web sockets and other real time events .It provides more functionality for performing event standard AJAX requests .Unlike Promises , the RxJS Observables sequences are cancellable. They can be easily chained, manipulated and configured.

Lets go through some basic terminology, and its functionality

Stream: A stream is a sequence of data elements that is available over time. Alternatively we can define it as a sequence of ongoing events that is ordered in time.Taking a real time example is number of click events processed in a second, so we can say it as all clicks to be grouped as a stream.

RxJS streams can be created using

From event

From promise

From callbacks

So here our main aim is to act on the streams, so we can say it as

"Stream is a subject which is observed"

Observable

In reactive programming Observer subscribes to an Observable. After that is reacts to the data what Observable emits.

We can make array , promise, or any iterable into an observable.

Converting to Observables

// From one or multiple values Rx.Observable.of('hello', 'world'); // From array of values Rx.Observable.from([1,2,3,4]); // From an event Rx.Observable.fromEvent(document.querySelector('button'), 'click'); // From a Promise Rx.Observable.fromPromise(fetch('/courses'));

Unsubscribing Observable

As observable execution can run infinite number of times , its important to stop it from executing. Since each execution is run for every subscribers , its good to not keep subscriptions open for subscribers, that don’t need it anymore as this may be a wastage of memory. When we subscribe to an observable , we get a subscription for the ongoing execution.So to unsubscribe it or to cancel it we need to call unsubscribe() method.

// Unsubscribe observable subscription Subscription.unsubscribe();

Example

let observable = Rx.Observable.create(function (observer) { observer.next(1); observer.next(2); setTimeout(() => { observer.next(4); observer.complete(); }, 500); }); console.log('before subscribe'); observable.subscribe({ next: x => console.log('value ' + x), error: err => console.error('something went wrong: ' + err), complete: () => console.log('done'), }); console.log('after subscribe');

. So we can say Observable is a representation of streams to act on .

. We can create Observable using Rx.Observable.create method which returns object having a subscribe method.

. Subscribe method takes an object as a param and this is what observer is.

.Observer is an object with next , error and complete methods on it.

RxJS Observable has many functions that creates Observables from promise , events, array of data etc.

Observer

When you subscribe to an observable , you are a observer. It can be a Object with next() , error(), complete() method, and it can be passed to an observable as below

observable.subscribe(observer)

There are 3 functions available to send data to the subscribers of the observable

“next” : emits values like, numbers, arrays, objects to subscribers.

emits values like, numbers, arrays, objects to subscribers. “error”: sends a javascript error or exception

sends a javascript error or exception “complete”: do not send any values

Subscribing to Observables :

Observable are lazy, if we don’t subscribe nothing will happen. Its important to know that when you subscribe to an Observer , each call of subscribe() will trigger its own independent execution for that given observer, Subscribe calls are not shared among multiple subscribers to the same observable.An Observable object begins publishing values only when someone subscribes to it.

We subscribe by calling subscribe() method of the instance, passing an observer instance to receive the notifications.

// Create simple observable that emits three values const myObservable = of(a, b, c, d); // Create observer object const myObserver = { next: x => console.log('Observer next value: ' + x), error: err => console.error('Observer error: ' + err), complete: () => console.log('Observer complete notification'), }; // Execute with the observer object myObservable.subscribe(myObserver); // Logs: // Observer got a next value: a // Observer got a next value: b // Observer got a next value: c // Observer got a next value: d // Observer got a complete notification

Note : A next() function receive for instance, message strings , event objects, numeric values or structures depending on context.