Reactive Programming with Observables in RxJS and Angular

We have seen that now a days reactive programming has changed the whole structure of how we develop our web application.Reactive programming is a programming paradigm that works with asynchronous data streams.It treats everything as a stream ordered in time and this stream can be generated by Http Requests, UI Events or array-like objects etc.

RxJS is one of the implementation in javascript of ReactiveX API.These API can be used with many others languages such as Java, C#, Python, PHP, ruby etc. It is a library for composing asynchronous and event-based programs by using observable sequences for reactive programming

In this post we will deep dive how RxJS observables are being used with Angular to do reactive programming and different operator which RxJs provides to handle the data well. So Let's start from observables first .

What are Observables ?  


Observables are nothing but a stream of data whose data arrive asynchronously.These data streams can be of anything - a stream of variables, properties, data structures or even stream of events. One can react to the stream by listening to it.

Observables are basically based on Observer Design Pattern. In Observer Design Pattern one-to-many dependency is maintained between the objects, when one object changes its state all other objects/dependents are notified. These dependents are known as Observers.

A stream can emit 3 different things:

1) Value
2) Error
3) Completed signal

Suppose that stream is a stream of events being observed. A function is defined that will be executed when a value is emitted, another function executes when an error is emitted and a third one once the complete signal is emitted. One can capture these events by using these functions. These functions are known as Observers and the stream which is being emitted is the Observable.

Observables are declarative—that is, you define a function for publishing values, but it is not executed until a consumer subscribes to it. The subscribed consumer then receives notifications until the function completes, or until they unsubscribe.

If you want to deep dive into the reactive programming , you can go to this link.

Observables can be of two types:

1.Hot - Hot observables are those which produce values even before their subscription gets activated. One can consider Hot Observables as live performance. The hot observable sequence is shared among each subscriber, also each subscriber gets the next value in the sequence.

2.Cold - Cold observables behave like standard iterators. They push values only when we subscribes to them and they reset when we subscribe again. One can consider Cold Observables as a movie.

From the above discussion , we can conclude that to understand the observables we need to understand the three terms properly i.e Publisher, Observer and Subscriber. Let's understand them one by one.

Publisher :

As a publisher, you create an Observable instance that defines a subscriber function. This is the function that is executed when a consumer calls the subscribe() method. The subscriber function defines how to obtain or generate values or messages to be published.

Observer :

A handler for receiving observable notifications implements the Observer interface. It is an object that defines callback methods to handle the three types of notifications that an observable can send:

next   :  Required. A handler for each delivered value. Called zero or more times after execution starts.

error :  Optional. A handler for an error notification. An error halts  execution of the observable instance.

complete  :  Optional. A handler for the execution-complete notification. Delayed values can continue to be delivered to the next handler after execution is complete.


Subscriber : 

An Observable instance begins publishing values only when someone subscribes to it. You subscribe by calling the subscribe() method of the instance, passing an observer object to receive the notifications.

Lets combine all of above and  see an example of creating and subscribing to a simple observable, with an observer that logs the received message to the console:

In this example we are using the Factory Method (Observables.of()) provided by RxJs to create the Observables. There are other Factory Method as well, which are generally used to create the Observables like

1) Observales.from()
2) Observables.fromEvent()
3) Observables.interval() 



Alternatively, the subscribe() method can accept callback function definitions in line, for next, error, and complete handlers. For example, the following subscribe() call is the same as the one that specifies the predefined observer:


In either case, a next handler is required. The error and complete handlers are optional.

Note that a next() function could receive, for instance, message strings, or event objects, numeric values, or stuctures, depending on context. As a general term, we refer to data published by an observable as a stream. Any type of value can be represented with an observable, and the values are published as a stream.

Creating Observables using constructor 


Use the Observable constructor to create an observable stream of any type. The constructor takes as its argument the subscriber function to run when the observable’s subscribe() method executes. A subscriber function receives an Observer object, and can publish values to the observer's next() method.


Common Operator Used with Observables 

There are many functional operators that can be used to combine Observables, so let's focus here on some of the most commonly used ones and how they can be used in an Angular application.

1) map()
2) filter()
3) pipe()
4) switchMap()

Map operator


The map operator is probably the most well-known functional programming operator out there, and Observable of course provides it. The map operator simply takes an Observable, and adds a transforming function that processes the output of the stream. For example:


It's important to realize that the output of map is still another observable. What we have here is still only a definition of an operation chain. We still need to subscribe to this observable to get an output out of it.

Pipe Operator 


Pipes let you combine multiple functions into a single function. The pipe() function takes as its arguments the functions you want to combine, and returns a new function that, when executed, runs the composed functions in sequence.

We can use the pipe operator and combine the above two operator as in below example.


How does Angular use Observables

Angular currently uses RxJs Observables in two different ways:

  • as an internal implementation mechanism, to implement some of its core logic like EventEmitter
  • as part of its public API, namely in Forms and the HTTP module

This is all from this post, in the next post we will deep dive more how angular use Observables .If you have any question or you want to add anything then please comment below.

Comments

Popular posts from this blog

Deploy standalone Spring MVC Application in Docker Container

Refactor Code : Separate Query from Modifier

HTTP : Must known Protocol (Part 1)