DEV Community

Cover image for A little conversation about RxJs Operators and some examples
Renan Ferro
Renan Ferro

Posted on • Updated on

A little conversation about RxJs Operators and some examples

Hi guys!

Today I want to show you some what RxJs Operators are some interesting operators so let's start!

RxJs Operators

First, let me show you what RxJs Operators are in a nutshell, RxJs Operators are functions, they allow us to do interesting things with our data, and we have two types of operators:

Pipeable operators

The Pipeable operators can be called using the using the syntax observableInstance.pipe(operator()). They receive an Observable and generates a new Observable as output. So, they don't change the existing Observable instance because they create a new one as output.

Creation operators

This one can be called as standalone functions to create a new Observable. They can to receive a number as argument and to create an Observable as output.

So, let's see some operators!

tap()

This one in my opinion is very interesting and simple. You can see the an exact data mirror of the source in your console.log.

import { of, tap } from 'rxjs';

const source = of('Angular', 'Typescript', 'RxJs');

const exampleTap = source.pipe(
   tap(val => console.log(`Technologies: ${val}`)),
);

const subscribe = exampleTap.subscribe();

//Output: Technologies: Angular... Technologies: Typescript... Technologies: RxjS
Enter fullscreen mode Exit fullscreen mode

map()

This is one of the most important operator in my opinion, because with it you can do many things, for example: to sanitize your API Response. It's like Array.prototype.map(), it receive each source value and with a transformation function and emits the resulting values as an Observable.

// My API Response

[
 {
   "cityNameAPIResponse": "New York"
 },
 {
   "cityNameAPIResponse": "Texas"
 }
]
Enter fullscreen mode Exit fullscreen mode
import { of, map } from 'rxjs';

// City is my class with nameCity property.

const exampleMap = myResponseCitiesAPIObservable.pipe(
  map((myCities) => {
    new City(myCities)
  })
);

subscribe = exampleMap.subscribe();

// OutPut Sanitized
//[
// {
//   nameCity: "New York"
// },
// {
//   nameCity: "Texas"
// }
//];
Enter fullscreen mode Exit fullscreen mode

distinct()

The distinct() operator returns a "clean" Observable, because it returns an Observable with values ​​that are not repeated by comparing previous items.

import { of, distinct } from 'rxjs';

const myCoursesObservable = of('Angular', 'Typescript', 'Angular', 'Typescript');

const exampleDistinct = myCoursesObservable.pipe(
  distinct(),
  tap(val => console.log(`Distinct Courses: ${val}`)),
);

 subscribe = exampleDistinct.subscribe();

//Output: Distinct Courses: Angular
//Output: Distinct Courses: Typescript
Enter fullscreen mode Exit fullscreen mode

take()

The take() operator is cool when you need to take a specific number of items as you can pass an amount and it returns an Observable with the specific number of items passed.

import { of, take } from 'rxjs';

const myIngredientsObservable = of('Banana', 'Orange', 'Milk', 'Apple');

const exampleTake = myIngredientsObservable.pipe(
   take(2),
   tap(val => console.log(`Just some ingredients: ${val}`))
);

const subscribe = exampleTake.subscribe();

//Output: Just some ingredients: Banana
//Output: Just some ingredients: Orange
Enter fullscreen mode Exit fullscreen mode

switchMap()

The switchMap() in an important RxJs operator and commonly used. It maps each value and creates a new intern Observable. So, the term switch is because we are switching from the source observable to an internal Observable and the Map s because we are mapping the emitted source value to a new observable, and a nice cool is the canceling effect available when we use switchMap().

import { of, switchMap } from 'rxjs';

const myGreetings = of('Hello guys, this is as awesome text!');

const exampleMap = myGreetings.pipe(
  switchMap((text: string) => {
    return of(text + ' Yeahh! A nice text :D');
  }),
    tap(val => console.log(`My new greetings: ${val}`))
);

const subscribe = exampleMap.subscribe();

// Output: My Favorite Cars: My new greetings: Hello guys, this is as awesome text! Yeahh! A nice text :D
Enter fullscreen mode Exit fullscreen mode

filter()

The filter() operator is nice because it's like Array.prototype.filter(), so you can pass a predicate to satisfy your your need and get only the items you need from the source Observable.

import { of, filter } from 'rxjs';

const myColorCarsCollection = of('Yellow BWM', 'Red BWM', 'Red BWM', 'Black BWM', 'Dark Blue BWM');

const exampleFilter = myCarColorCollection.pipe(
  filter(myCarColorCollection => myCarColorCollection.includes('Yellow') ||  myCarColorCollection.includes('Blue')),
  tap(val => console.log(`My Favorite Cars: ${val}`))
);

const subscribe = exampleFilter.subscribe();

// Output: My Favorite Cars: Yellow BWM
// Output: My Favorite Cars: Dark Blue BWM
Enter fullscreen mode Exit fullscreen mode

debounceTime()

The debounceTime() is like delay, because it returns an Observable that delays the emissions of the Observable source by the specified. So, when you have a search input in your app and you use an API you can use debounceTime(1000) and and the user will be able to write the full word for the search and you don't make unnecessary requests.

import { fromEvent, debounceTime } from 'rxjs';

const searchInputField = document.getElementById('search-input');

const clientSearch$ = fromEvent(searchInputField, 'keypress');

clientSearch$
   .pipe(
      map((searchInput: any) => {
         searchInput.currentTarget.value
      }),
      debounceTime(500)
   )
   .subscribe(
     console.log
   );

// Output after 500: Car
Enter fullscreen mode Exit fullscreen mode

repeat()

The repeat operator it's very simple and very useful in some cases, as you can pass a number as a parameter to the repeat() operator and it will repeat the Observable with the specified number.

import { of, repeat } from 'rxjs';

const justMyTeam = of('Minnesota Vikings');

const exampleRepeat = justMyTeam.pipe(
  repeat(3),
  tap(val => console.log(`My team: ${val}`))
);

const subscribe = exampleRepeat.subscribe();

//Output: My team: Minnesota Vikings
//Output: My team: Minnesota Vikings
//Output: My team: Minnesota Vikings
Enter fullscreen mode Exit fullscreen mode

So, that's it guys! Obviously there are many others nice operators and you can see it here. I hope you enjoyed the article and it helped you!

And lastly, have you ever needed to make a cascade list animation with your cards!? If yes, take a look in this article.

Bye guys, thank's for your time and see you soon!

Top comments (0)