RxJS: Most commonly used operators
RxJS provide different types of operators some important operators are defined here.
SWITCH MAP
The switch Map operator maps each value to an observable, then it patterns all of the internal observables.
Example of Switch map
import { fromEvent, interval } from 'rxjs';
import { switchMap } from 'rxjs/operators';
const obs$1 = fromEvent(document, 'click');
const obs$2 = interval(1000);
const finalObs$ = obs$1.pipe(
switchMap(event => obs$2)
);
const subscription = finalObs$.subscribe((value) => console.log(value));
When subscribed, obs$1 will emissions a response for every user clicks on the page and obs$2 will increment emission numbers for every 1 sec.
MERGE MAP
Merge Map by default is a combination of merge All and map. Merge All takes care of subscribing to the 'internal' Observable so that we no longer have to Subscribe two times as merge All merges the value of the 'internal' Observable into the 'outer' Observable.
Example of Merge map
import { mergeMap, map } from 'rxjs/operators';
const firstNameObs$ = of('kinnari');
const lastNameObs$ = of('parmar');
const finalObs$ = firstNameObs$.pipe(
mergeMap(event1 => lastNameObs$.pipe(map(event2 => event1+' '+event2)))
);
const subscription = finalObs$.subscribe((value) => console.log(value)
THROTTLE TIME
This operator is used to emission the latest value when a specified throttle time duration has passed.
Example of Throttle time
import { interval } from 'rxjs';
import { throttleTime } from 'rxjs/operators';
const obs$ = interval(1000).pipe(
throttleTime(3000));
obs$.subscribe(console.log)
In which the Output is Shown as 0,4,8,12….
MAP & PLUCK
Map and Pluck are the most used and very useful operators in the RxJS. Map operator in RxJS works same as JS map. Pluck is used when we just need to passed a single field value to the subscription otherwise sending the entered JSON object.
Example of Map & Pluck
import { from } from 'rxjs';
import { pluck } from 'rxjs/operators';
const data = [{id:1, value:'one'}, {id:2, value:'two'}, {id:3, value:'three'}];
const obsPluck$ = from(data).pipe(
pluck('value')
).subscribe(x =>console.log(x));
const obsMap$ = from(data).pipe(
map(data => data.value)
).subscribe(x => console.log(x));
Here Output Shown as one two three ….