Rxjs Operators : –
RxJS is the utmost helpful for those operators, even if it is observable concept also. Operators are the eminent pieces that allow critical asynchronous code to simply collect in an understandable manner.
Now, We can see some of the most useful operators in daily usage projects like map, filter, mergeMap, switchMap
Importing the Operators into application
If you are using the RxJS version 5.4.x then you can use prototype-based importions
import ‘rxjs/add/operators/operatorName;
If you are using RxJS version 5.5.x then you can go for ES6 import style of exported function like below,
import { operatorName } from ‘rxjs/operators’;
Note:- Here, operatorName are rxjs operators like filter, map, mergeMap and etc.
Usage and Importance
Filter:-
Like Array.prototype.filter(). It will emit the values only based on the predicate conditions which means it will get the values from the source observable and will emit the values when the passed condition is true.
Import:
import ‘rxjs/add/operators/filter’ ( Or ) import { filter } from ‘rxjs/operators’
Example:-
persons = from([{ name: 'person1', age: 22, sex: 'm', }, { name: 'person2', age: 26, sex: 'm', }, { name: 'person3', age: 20, sex: 'f', } ]); const filterOnAge = this.persons.pipe(filter(person => person.age == 20 )); filterOnAge.subscribe(val=> console.log(val))
Output:
{name: "person3", age: 20, sex: "f"} const filterOnSex = this.persons.pipe(filter(person => person.sex == 'm')) filterOnSex.subscribe(val=> console.log(val)) Output :- {name: "person1", age: 22, sex: "m"}, {name: "person2", age: 26, sex: "m"}
Note: ‘from’ is also rxjs keyword. It will transfer an array, iterable or promise into an observable
You can check the output here:
Stackblitz url: https://stackblitz.com/edit/angular-filter-in-rxjs?file=src/app/hello.component.ts
Map:-
We are well known about Array.prototype.map() function and this function is similar like this. This operator applies projection to each value from input data and emits that as output observable. And also, it’s plucking particular data values into an array.
Import:
import ‘rxjs/add/operators/map ( Or ) import { map } from ‘rxjs/operators’
Example:-
sports = from([ { name: 'cricket', selected: true }, { name: 'vollyball', selected: false }, { name: 'koko', selected: false } ]); const selectedSports = this.sports.pipe(map((sport) => sport.selected = true)); const subscribe = selectedSports.subscribe(val => console.log(val));
Output
true, true, true const sportsNames = this.sports.pipe(map((sport) => sport.name); const subscribe = sportsNames.subscribe(sport => console.log(sport));
Output
Cricket, vollyball, koko
Output Link : https://stackblitz.com/edit/angular-rxjs-map?file=src%2Fapp%2Fhello.component.ts
SwtichMap :-
It will map each value to an observable, then it will flattens all of these inner observables using ‘switch’.
Import:-
import ‘rxjs/add/operators/switchMap’; Or import { switchMap } from ‘rxjs/operators’;
Example:
// ‘of’ is oberservableof rxjs, it will emitting the values in sequence.
import { of } from 'rxjs/observable/of'; const source = of('Hello', 'Hai'); //switchMap also emits result of promise const myPromise = val => new Promise(resolve => resolve(`${val} World From Promise!`)); //map to promise and emit result const example = source.pipe(switchMap(val => myPromise(val))); //output: 'Hai World From Promise' const subscribe = example.subscribe(val => console.log(val));
Stackblitz url: https://stackblitz.com/edit/angular-rxjs-switchmap?file=src%2Fapp%2Fhello.component.ts
Returns the output observable that emitted based on the function you apply on each item emitted by source observable. Whenever it calls the new inner subscription then it will cancel the previous inner subscriptions and it will emit the recent subscription. If you want only one inner subscription to get active at a time then go for ‘switchMap’ otherwise go for ‘mergeMap’ if you want multiple inner subscriptions at a time.
MergeMap: –
It is also known as flatMap. It maps each value to an observable, then it will flattens all of these inner subscriptions using ‘mergeall’
Import:-
import ‘rxjs/add/operators/mergeMap’; Or Import { mergeMap } from ‘rxjs/operators’
Example:
//‘of’ is oberservableof rxjs, it will emitting the values in sequence import { of } from 'rxjs/observable/of'; const source = of('Hello', 'Hai'); //mergeMap also emits result of promise const myPromise = val => new Promise(resolve => resolve(`${val} World From Promise!`)); //map to promise and emit result const example = source.pipe(mergeMap(val => myPromise(val))); //output: 'Hello World From Promise', 'Hai World From Promise' const subscribe = example.subscribe(val => console.log(val));
Stackblitz Link: https://stackblitz.com/edit/angular-rxjs-mergemap?file=src/app/hello.component.ts
Returns the output observable that emitting based on the given function that you apply each item emitted by source observable. It will handle multiple inner subscriptions at a time. So, Some times it will create memory leak problem because of long time active subscriptions. To avoid this conflictions, better you can go to ‘concatMap’. concatMap won’t go to next subscription untill previous subscription completes so there would be less possibility for memory leaks.
If you like to read more blogs about web development or recent technologies like Blockchain, IOT & upcoming trends then keep your eye on our largest blog repository which could help you with more technical blogs.
For any queries reach us via info@agiratech.com