RxJS Operators

Chetan Chauhan
6 min readOct 3, 2021

Modern web apps of today are heavily event-driven, meaning they react to (and rely on) a range of external services and data sources to make them tick. One of the core libraries to make this happen is ReactiveX, also known as Reactive Extensions.

The ReactiveX library has been implemented in a range of languages, the most widely adopted of which being RxJS, the JavaScript implementation. RxJS is particularly useful as it can be integrated within any JavaScript application, whether server or client side, this has contributed to its huge growth in adoption.

In this document we will cover a few of the RxJS operators with example which help in dealing with streams.

Following is the editor url for all the implementation examples shown below:-

https://stackblitz.com/edit/js-scltlz

Interval, take and pipe

Interval emits a sequence of values starting from zero in the provided interval of time which is passed as a parameter.

Take operator returns an Observable that emits only the first count(passed as parameter) values emitted by the source Observable to it. If the source emits fewer than count values then all of its values are emitted.

Pipe operator is used to implement one or more operators together on an observable. By pipe we can chain multiple operators to an observable. In the above example we are using a pipe with one operator(take as a parameter) only, it can also take multiple operators.

timer and takeUntill

Timer operator creates an observable which emits a single value after a specified time.

Take operator takes number of values as per the count passed to it as a parameter while takeUntill operator takes number of values emitted during the timer passed to it as a parameter.

Same has been demonstrated in below example:-

Here we are creating a observable source which will emit value every 1 second and a timer with value 5 sec. We are passing timer as a parameter to takeUntill operator which will listen to values until 5 seconds then complete the source when 5 second completes (hence no value 4 is printed).

Of

Of operator returns an Observable which immediately emits whatever values are supplied as parameters when it is subscribed to and then completes. It can take multiple parameters.

From

From operator can be used to generate an observable from an array , promise or iterable.

Of vs From

The difference between of and from is the way in which arguments are passed. From will only accept argument as an array, promise or observable and emit their values one by one. Of can accept these also but will emit it as a single value. So if you pass an array to of , it will emit whole array at once while from will emit array’s value one by one.

Pluck

Pluck is used when we just need to pass a single field value to the subscription instead of sending the entire JSON object. We need to pass the key of the required field as a string argument to pluck operator.

In above example, pluck is used to only pass brand from the each JSON object from observable array further to the subscription.

Map

If you have used the map method with Arrays in JS, you’ll be able to relate to it more easily. Map operator is one of the commonly used operators while dealing with observables. Map operator allows us to perform an operation on every emitted value of an observable. It takes an accumulator function containing logic to be implemented for observable values as parameters and then subscription will receive the modified values.

mergeMap

MergeMap is also used for mapping data but it is useful in specific scenarios where you are dealing with nested observables.

Let us assume you have an observable array for whose values you want to perform an operation which will result also in an observable form. So in that case we will have to subscribe to both outer and inner observables. Mergemap helps us in that case as it subscribes to the inner observable and we only have to subscribe once for the outer observable.

In the above example we are creating a method fakeApiCall which will create an observable of type string concatenating the id received as parameter to it and using delay operator to send response after a specific period of time i.e. 1000ms. Then we have created an observable of type array via “from” operator to act as a dataset.

In the first implementation without mergeMap, we are using map operator to call fakeApiCall method for each value in the observable array dataset which returns an observable of type string which will act as inner observables. So we are doing two subscriptions here, first for outer observable and then for inner observable to print the result in the console.

While in second implementation where we have used mergeMap instead of map we have to subscribe to outer observable only as mergeMap is taking care of the inner observable.

SwitchMap

SwitchMap also subscribes to the inner observable like mergeMap does. But the difference between the two is that according to switchMap behavior, it cancels the previous subscriptions and only handles the last one. So if we apply switchMap instead of mergeMap in our previous example it will only print the response for last id in dataset.

ConcatMap

Like MergeMap and SwitchMap, It also subscribes to the inner observable. The key behavior of concatMap is that it preserves the order in which the Observables are emitting.

In the above example we have created the same fakeApiCall method but this time we are generating a random value of time for delay so that all values are emitted in different time durations.

As we can see in the console that order is maintained for all the values despite them being emitted at random timings.

forkJoin

This operator can be used in the scenario where you need to execute some logic only when the response has been received for all the observables.

In above example we are returning an object with result of all three observables via forkJoin. Handler in subscription is only executed when all three observable have emitted an value.

DebounceTime & DistinctUntilChanged

DebounceTime operator is used in scenarios such as type-ahead where the rate of user input must be controlled.

debounceTime(1000) will make the observable wait for 1 sec before it can emit users input.

DistinctUntilChanged operator when used along with debounceTime will make observable only output distinct values.

In above time we have generated an event observable from input event of input/textbox element of dom via fromEvent operator and then we have retrieved value of the input from emitted event via map operator. We have used map and debouncetime operators via the help of pipe. DebounceTime is making sure here that value is emitted only after there is a pause of 600 ms.

ThrottleTime

It is used to emit the latest value when a specified time duration has passed. Difference between it and debouncetime is that throttleTime does not wait for the pause. Below is previous example using throttleTime operator:-

--

--