App Development RxJS

RxJS – Part 1: Introduction to RxJS – Higher-Order Observables

Introduction to RxJS

RxJS is a great tool for the front-end developers in problem solving. With RxJS, we can handle many series of events and tackle it to our own needs.

In this two-part blog series, we’ll briefly discuss on ‘Introduction to RxJS’ and ‘Higher-Order Mapping’. RxJS is a library for reactive programming for making asynchronous network calls easier using observables and several operators. In Reactive Programming, RxJS Higher-Order Mapping Operators play a very crucial role in solving many operations. 

The most commonly used RxJS higher-order mapping operators are switchMap, mergeMap, concatMap and exhaustMap. You might be doubted where to use these operators.  It will be clear once you have gone through the different operators in the next part of the blog, where the functionality for each of them will be explained.

Higher-Order Observables

Before learning more about higher-order mapping operators, let’s first have a brief look into higher-order observables. The response from an Http request might be a stream of data of simple types such as numbers or strings; complex types such as arrays or objects. This stream can be caused due to some user input events(mouse or keyboard) and using RxJS we will be handling these streams of data. Observable or stream refers to a collection of data items that can be emitted synchronously or asynchronously. 

Now when talking about higher-order observables, these are the observables that emit other observables. Let’s understand more about this through an example. Suppose in our application there is an Apply button which invokes an apply() method when clicking on it. Let’s have a look into the code snippet below:

fromEvent(applyBtn, 'click')

    .pipe(map(click => apply()))

    .subscribe(response => {

        //response is a stream of data

    });

 

Here before we subscribe to the response of the click event, we map into the apply method which returns an Observable itself. This is the outer stream. Observable emitting from the response of the apply method is called the inner stream. So here we have observables which emit other observables and this is higher-order observables.  

When we subscribe to the response of the apply method, the Http call will return Observable streams. When mapping the stream of function calls, we’ll again get observable streams. So to get the final response, we need to subscribe to the observables again. This kind of nested subscriptions is complex to handle and we need to flatten these types of higher-order observables to first-order observables for easier processing. Here comes the role of higher-order mapping operators which we’ll discuss in the next blog- however, use it with utmost care. It will result in unintended complex output if we used it wrongly.