How to use RxJS operators to consume Observables in your workflow
Tags: rxjs, javascript, tutorial
Published: 2019-08-16 13:07:28

---
title: How to use RxJS operators to consume Observables in your workflow
published: true
tags: rxjs, javascript, tutorial 
canonical_url: https://blog.logrocket.com/use-rxjs-operators-to-consume-observables/
cover_image: https://thepracticaldev.s3.amazonaws.com/i/s8t6b084u68j9hrnsywx.png
---
**Written by [Nwose Lotanna](https://blog.logrocket.com/author/nwoselotanna/)**✏️

## RxJS

[RxJS](https://rxjs-dev.firebaseapp.com/) is a framework for reactive programming that makes use of Observables, making it really easy to write asynchronous code. [According to the official documentation](https://rxjs-dev.firebaseapp.com/), this project is a kind of reactive extension to JavaScript with better performance, better modularity, better debuggable call stacks, while staying mostly backwards compatible, with some breaking changes that reduce the API surface. It is the official library used by Angular to handle reactivity, converting pull operations for call-backs into Observables.

## Prerequisites

To be able to follow through in this article’s demonstration you should have:

- [Node version 11.0](https://nodejs.org/) installed on your machine
- Node Package Manager version 6.7 (usually ships with Node installation)
- [Angular CLI](https://cli.angular.io/) version 7.0
- The latest version of Angular (version 7)

```jsx
// run the command in a terminal
ng version
```

Confirm that you are using version 7, and update to 7 if you are not.

- Download this tutorial’s starter project [here](http://github.com/viclotana/ng_canvas) to follow through the demonstrations
- Unzip the project and initialize the node modules in your terminal with this command:

```jsx
npm install
```

## Understanding RxJS operators

Observables are the foundation of reactive programming in RxJS and operators are the best way to consume or utilize them. **Operators** are methods you can use on Observables and subjects to manipulate, filter or change the Observable in a specified manner into a new Observable. They provide a platform for complex logic to be run on Observables and gives the developer total control of the output of the Observables.

It is important to note that operators do not change the initial Observable, they just edit it and output an entirely new Observable.

[![LogRocket Free Trial Banner](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2017/03/f760c-1gpjapknnuyhu8esa3z0jga.png?resize=1200%2C280&ssl=1)](https://logrocket.com/signup/)

## Types of operators

According to the official RxJS documentation, there are two types of operators.

**A. Pipeable operators** : These are operators that can be piped to existing Observables using the pipe syntax.

```jsx
observableInstance.pipe(operator())
```

They are called on existing Observables and they do not change the Observable instance, they return a new Observable with a subscribe method based on the initial Observable.

**B. Creation operators** : These operators, on the other hand, create an Observable with either a pre-defined behavior or by joining more than one Observable together. They can be referred to as standalone methods that create new Observables.

## How operators work: Marble diagram

![how operators work](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2019/08/howoperatorswork.png?resize=640%2C396&ssl=1)<figcaption id="caption-attachment-4957"><a href="https://rxjs-dev.firebaseapp.com/guide/operators" target="_blank" rel="noopener noreferrer">https://rxjs-dev.firebaseapp.com/guide/operators</a></figcaption>

The image above shows a visual representation of how operators work. It is always a left to right and top-down progression. The Observable is first created and emits some values then at completion by the complete parameter, the defined operator takes the emitted values as input and then modifies them to give a brand new Observable.

## Categories of operators

There are over [100 operators in RxJS](https://rxjs-dev.firebaseapp.com/api) and they can be classified into various categories, some of these are creation, transformation, filtering, joining, multicasting, error handling and utility.

| Category | Operators |
| --- | --- |
| Creation Operators | ajax, bindCallback, defer, empty, from, fromEvent, fromEventPattern, generate, interval, of, range, throwError, timer and iif. There are join creation operators too like combineLatest, concat, forkJoin, merge, race and zip. |
| Transformation Operators | buffer, bufferCount, bufferTime, bufferToggle, bufferWhen, concatMap, concatMapTo, exhaust, exhaustMap, expand, groupBy, map, mapTo, mergeMap, mergeMapTo, mergeScan, pairwise, partition, pluck, scan, switchMap, switchMapTo, window, windowCount, windowTime, windowToggle, windowWhen. |
| Filtering Operators | audit, auditTime, debounce, debounceTime, distinct, distinctKey, distinctUntilChange, distinctUntilKeyChanged, elementAt, filter, first, ignoreElements, last, sample, sampleTime, single, skip, skipLast, skipUntil, skipWhile, take, takeLast, takeUntil, takeWhile, throttle and throttleTime. |
| Joining Operators | combineAll, concatAll, exhaust, mergeAll, startWith and withLatestFrom. |
| Multicasting Operators, Joining Operators | multicast, publish, publishBehaviour, publishLast, publishReplay and share. |
| Error Handling Operators | catchError, retry and retryWhen. |
| Utility Operators | tap, delay, delayWhen, dematerialize, materialize, observeOn, subscribeOn, timeInterval, timestamp, timeout, timeoutWith and toArray. |

## Popularly used RxJS operators

If you followed this post from the start, you will have a starter project opened up in VS Code to follow up with these illustrations. In this section you will be shown how to use a few top RxJS operators in your Angular  workflow:

### merge()

![merge](https://i1.wp.com/blog.logrocket.com/wp-content/uploads/2019/08/merge.png?resize=1280%2C740&ssl=1)<figcaption id="caption-attachment-4963"><a href="https://rxjs-dev.firebaseapp.com/guide/operators" target="_blank" rel="noopener noreferrer">https://rxjs-dev.firebaseapp.com/guide/operators</a></figcaption>

This operator is a join creation operator that simply merges one observable with another observable and returns the combination of them both as one Observable. Open your `app.component.ts` file and copy in the code block below:

```jsx
import { Component, OnInit } from '@angular/core';
import { Observable, merge} from 'rxjs';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  ngOnInit(){
   const observable1 = Observable.create((observer:any) => {
      observer.next('I am Observable 1')
  });
  
  const observable2 = Observable.create((observer:any) => {
      observer.next('I am Observable 2')
  });
  
  const observable3 = merge(observable1, observable2);
  
  observable3.subscribe((data) => console.log(data));
  }
}
```

Your browser console should look like this:

![observable in console](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2019/08/observableinconsole.png?resize=1386%2C376&ssl=1)

## of()

![of ()](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2019/08/createobservales.png?resize=1280%2C340&ssl=1)<figcaption id="caption-attachment-4969"><a href="https://rxjs-dev.firebaseapp.com/guide/operators" target="_blank" rel="noopener noreferrer">https://rxjs-dev.firebaseapp.com/guide/operators</a></figcaption>

This is creation operator used to create Observables from any kind of data, be it a string or an array, an object or even a promise. Test it out with this code block below:

```jsx
import { Component, OnInit } from '@angular/core';
import { Observable, of} from 'rxjs';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  ngOnInit(){
     const observable1 = of(1,2,3)
      .subscribe((data) => console.log(data));
 }
}
```

## map()

![map operator](https://i2.wp.com/blog.logrocket.com/wp-content/uploads/2019/08/map.png?resize=1024%2C432&ssl=1)<figcaption id="caption-attachment-4972"><a href="https://rxjs-dev.firebaseapp.com/guide/operators" target="_blank" rel="noopener noreferrer">https://rxjs-dev.firebaseapp.com/guide/operators</a></figcaption>

This is an operator defined in a pipe inside which you can modify the content of emitted values from one observable to form another new observable. In your `app.component.ts` file copy in the code block below:

```jsx
import { Component, OnInit } from '@angular/core';
import { Observable, of} from 'rxjs';
import { map } from 'rxjs/operators';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  ngOnInit(){
const observable1 = of('my name is lotanna');
  observable1.pipe(
    map(data => data.toUpperCase())
  ).subscribe((data) => console.log(data));
}}
```

Inside the pipe, you can then add your modification logic, in our case it is to convert the emitted values to upper case.

## fromEvent()

![fromEvent](https://i1.wp.com/blog.logrocket.com/wp-content/uploads/2019/08/fromEvent.png?resize=1280%2C340&ssl=1)<figcaption id="caption-attachment-4987"><a href="https://rxjs-dev.firebaseapp.com/guide/operators" target="_blank" rel="noopener noreferrer">https://rxjs-dev.firebaseapp.com/guide/operators</a></figcaption>

This operator takes any DOM element and an event name as props and then creates a new observable with it. A simple document click operator will look like this:

```jsx
import { Component, OnInit } from '@angular/core';
import { fromEvent} from 'rxjs';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  ngOnInit(){
const observable1 = fromEvent(document, 'click')
  .subscribe(() => console.log('You clicked the page!'));
}}
```

## pluck()

![pluck operators](https://i2.wp.com/blog.logrocket.com/wp-content/uploads/2019/08/pluck.png?resize=1024%2C432&ssl=1)<figcaption id="caption-attachment-4990"><a href="https://rxjs-dev.firebaseapp.com/guide/operators" target="_blank" rel="noopener noreferrer">https://rxjs-dev.firebaseapp.com/guide/operators</a></figcaption>

Just as the name implies, the pluck operator plucks a single property from an array that has multiple properties. Here is a quick example:

```jsx
import { Component, OnInit } from '@angular/core';
import { from } from 'rxjs';
import { pluck } from 'rxjs/operators';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  ngOnInit(){
from([
    { brand: 'iPhone', model: 'Xmax', price: '$1000'},
    { brand: 'Samsung', model: 'S10', price: '$850'}
])
.pipe(
  pluck('price')
)
.subscribe((data) => console.log(data));
}}
```

## take()

![take operator](https://i1.wp.com/blog.logrocket.com/wp-content/uploads/2019/08/take2.png?resize=1280%2C540&ssl=1)<figcaption id="caption-attachment-4994"><a href="https://rxjs-dev.firebaseapp.com/guide/operators" target="_blank" rel="noopener noreferrer">https://rxjs-dev.firebaseapp.com/guide/operators</a></figcaption>

This operator takes the very occurrence of emitted events in an observable. So for instance, we already worked on a fromEvent operator for a page click. With the take operator, the new observable can only record the very first click.

```jsx
import { Component, OnInit } from '@angular/core';
import { fromEvent } from 'rxjs';
import { take } from 'rxjs/operators';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  ngOnInit(){
const observable1 = fromEvent(document, 'click')
 .pipe(
   take(2)
 )
  .subscribe(() => console.log('You clicked the page!'));
}}
```

This records only the first two clicks on the page as expected.

## Conclusion

This article introduces RxJS operators as the main character in reactive programming. Observables are the foundation and the operators are the methods that help us consume Observables properly. We also looked at categories of operators and how to use some of the very popular ones. Happy hacking!
* * *
**Editor's note:** Seeing something wrong with this post? You can find the correct version [here](https://blog.logrocket.com/use-rxjs-operators-to-consume-observables/).

## Plug: [LogRocket](https://logrocket.com/signup/), a DVR for web apps
 
![LogRocket Dashboard Free Trial Banner](https://i2.wp.com/blog.logrocket.com/wp-content/uploads/2017/03/1d0cd-1s_rmyo6nbrasp-xtvbaxfg.png?resize=1200%2C677&ssl=1)
 
[LogRocket](https://logrocket.com/signup/) is a frontend logging tool that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.
 
In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.
 
[Try it for free](https://logrocket.com/signup/).
* * *
The post [How to use RxJS operators to consume Observables in your workflow](https://blog.logrocket.com/use-rxjs-operators-to-consume-observables/) appeared first on [LogRocket Blog](https://blog.logrocket.com).