Tech Incent
Angular

Most Commonly Used RxJS Operators With Example

#1 Map operator

The map operator is a very simple rxjs operator that allows us to grab the data each and every time event is emitted or observable and manipulate data how to every we like. that manipulate data return the rest of the observable pipe operator if you have any left.

Example:

fromEvent(document, 'click')
  .pipe(
    map((event: MouseEvent) => {
      return [event.clientX, event.clientY];
    })
  )
  .subscribe(data => {
    console.log('clint x and y', data);
  });

#2 Tap Operator

Tap operator is very similar to map operator but tab operator that gives you a copy every data is coming through from pipe so when you manipulate data in your tab operator you can’t affect outcome rest of your pipe. To use tap operator debug and console log the data in your screen

fromEvent(document, 'click')
  .pipe(
    tap((event: MouseEvent) => {
      return event.clientX;
    })
  )
  .subscribe(data => {
    console.log(data);
  });

#3 SwitchMap Operator

switchMap operator like all other rxjs operators starts by observing some outer source observable. then we are able to power the switchMap operator, add a result or inner obserable in that operating. whenever our source is obserable or outer obserable, switchMap cancels the current stream and starts a new event stream. and then any other pipe operator below the switchMap, just be dealing with the result of switchMap Obserable.

Let clear with an example:

fromEvent(document, 'click')
  .pipe(switchMap(() => interval(1000)))
  .subscribe(() => console.log);

Note: interval is another rxjs operator. which makes obserable interval.

#4 TakeUntil Operator

takeUntil operator is required a secondary obserable to watch and the secondary obserable fire an event that takes until cancel source obserable.

Example:

interval(1000)
  .pipe(takeUntil(fromEvent(document, 'click')))
  .subscribe(() => console.log);

#5 Filter Operator

filter operator allows us to filter out specific data through the pipe base on the criteria that we provide. filter operator is taken a boolean expression that a result emits the true or false value

fromEvent(document, 'click')
  .pipe(filter((event: MouseEvent) => event.clientX > 500))
  .subscribe(() => console.log('clicked clint x 500 area'));

Related posts

Angular Bootstrap 5 Popup Registration Form

Sajal Mia

Angular Search and pagination with example

Sajal Mia

Implement angular (product) details page with reactive service

Sajal Mia

Angular bootstrap date picker example

Sajal Mia

Angular Date as ago (minutes / hours / days / months / years ago) pipe

Sajal Mia