current position:Home>5 marbles to thoroughly understand the leveling strategy of rxjs: mergemap, switchmap, concatmap and exhaustmap
5 marbles to thoroughly understand the leveling strategy of rxjs: mergemap, switchmap, concatmap and exhaustmap
2022-04-29 20:30:56【Voyager 1 technical team】
RxJS The operator of is really complex to understand , For example, the most commonly used map The operator , In this article, let's rush at them !!
- Original article , For non-commercial reprint, please name the source
map The operation must be familiar to everyone :
const { of } = Rx;
const { map } = RxOperators;
const namesObservable = of('A', 'B');
namesObservable.pipe(
map(name => `map ${name}`)
)
namesObservable .subscribe(result => console.log(`${result}`))
// map A
// map B
Copy code
intuitive , because map Mapped is “ value ”, So it's simple enough ~
however , if ,map Mapped is observable Well ?
const { of } = Rx;
const { map } = RxOperators;
const namesObservable = of('A', 'B');
const http =(name)=>{
return of(`${name} 1`,`${name} 2`);
}
namesObservable.pipe(
map(name => http(name))
)
namesObservable.subscribe(result => console.log(`${result}`))
// You'll get two observable object
// ****observable{ .. }
// observable{ .. }
Copy code
We are rxviz.com/ In the picture of marbles , Can be seen clearly : It is still observable
also observable From the original 1 individual , Turned into 2 individual ( The circle is observable), The data is still inside and has not been parsed by the subscription .
although , We can use Brutal Methods , The subscription .subscribe
Call the subscription again .subscribe
, Then the value can be obtained :
const { of } = Rx;
const { map } = RxOperators;
const namesObservable = of('A', 'B');
const http =(name)=>{
return of(`${name} 1`,`${name} 2`);
}
namesObservable.pipe(
map(name => http(name))
)
namesObservable .subscribe(resultObservable => {
resultObservable.subscribe(result => console.log(`${result}`) )
})
// A1
// A2
// B1
// B2
Copy code
however , This kind of package writing is doomed to be inelegant , therefore , To solve this difference ,RxJS Introduced —— Flattening( flat ) Strategy !!
We can use flatMap The operator , The same analytical value can be obtained ~
flatMap In fact, we are well-known mergeMap The operator ;
The code is as follows :
const { of } = Rx;
const { mergeMap} = RxOperators;
const namesObservable = of('A', 'B');
const http =(name)=>{
return of(`${name} 1`,`${name} 2`);
}
namesObservable.pipe(
mergeMap(name => http(name))
)
namesObservable.subscribe(result => console.log(`${result}`))
// A1
// A2
// B1
// B2
Copy code
Further more , Follow this kind of flattening strategy , except mergeMap,RxJS And the introduction of switchMap、concatMap and exhaustMap, They can provide leveling strategies in different directions .
Let's use rxviz.com/ Marbles map , You can see their differences at a glance :
Set a timer , Every second sends a observable, A total of 3 Time , Let's take a look at the respective values ;
- mergeMap
const { of,interval} = Rx;
const { mergeMap,take,map } = RxOperators;
const namesObservable = of('A', 'B');
const http =(name)=>{
return interval(1000)
.pipe(
take(3),
map(()=>of(`${name} 1`,`${name} 2`))
)
}
namesObservable.pipe(
mergeMap(name => http(name))
)
Copy code
mergeMap
Internal subscriptions for multiple activities will be maintained at the same time ;
- switchMap
const { of,interval} = Rx;
const { switchMap,take,map } = RxOperators;
const namesObservable = of('A', 'B');
const http =(name)=>{
return interval(1000)
.pipe(
take(3),
map(()=>of(`${name} 1`,`${name} 2`))
)
}
namesObservable.pipe(
switchMap(name => http(name))
)
Copy code
switchMap
, Every time it's sent out , Will cancel the previous internal observable The subscription , Then subscribe to a new observable;
- concatMap
const { of,interval} = Rx;
const { concatMap ,take,map } = RxOperators;
const namesObservable = of('A', 'B');
const http =(name)=>{
return interval(1000)
.pipe(
take(3),
map(()=>of(`${name} 1`,`${name} 2`))
)
}
namesObservable.pipe(
concatMap (name => http(name))
)
Copy code
concatMap
Will be in the previous interior observable After completion , Will subscribe to the next ;
- exhaustMap
const { of,interval} = Rx;
const { exhaustMap ,take,map } = RxOperators;
const namesObservable = of('A', 'B');
const http =(name)=>{
return interval(1000)
.pipe(
take(3),
map(()=>of(`${name} 1`,`${name} 2`))
)
}
namesObservable.pipe(
exhaustMap (name => http(name))
)
Copy code
exhaustMap
Map to internal observable, Ignore other values until this observable complete ;
OK, The above is the sharing of this article .
Think it's good. Give it a compliment , Your encouragement , My motivation , Adhere to the output quality of good articles ~~ Welcome to comment and discuss
I'm Anthony nuggets , The output exposes the input , Technical insight into life . Goodbye ~~
copyright notice
author[Voyager 1 technical team],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/04/202204292030522936.html
The sidebar is recommended
- Talking about nodejs server
- Node. js< I & gt—— Encounter node and repl usage
- Vue basic API: calculation attribute + filter + listener
- 1-stm32 + mn316 (nb-iot) remote upgrade OTA (self built Internet of things platform) - STM32 uses HTTP to download program files and upgrade programs through mn316 (MCU program rotation check and update)
- Vue Axios response interception
- vue3 ref
- How does Vue transfer the data from the parent component to the child component intact?
- The back-end interface developed by springboot in idea and the Vue front-end developed by vscode. How to integrate Vue code into springboot?
- Fried cold rice series 4: scope and closure in JavaScript
- Typescript type compatibility learning
guess what you like
Summary of bugs encountered in front-end development
Chrome developer tool: performance analysis using web panel
Collation of common semantic elements and global attributes in HTML
Life cycle in Vue
5.1 fear of traffic jam? With a budget of less than 100000, these cars with adaptive cruise make it easy for you to travel
Docker compose deploy nginx configure SSL
The content of element type “mapper“ must match “(cache-ref|cache|resultMap*|parameterMap*|sql*|inse
-CSS-
Vue uses two-way binding to implement the user registration page
Is Infiniti qx60 worth less than 400000 yuan? It depends on the discount
Random recommended
- "Element Fangjian: first heart version" public beta welfare release, go to the great God app to receive red envelopes and prizes
- What is the role of webpack cli in webpack packaging
- Vue3 configuration method using Axios
- How to configure Google reverse proxy on nginx server
- Volume comparison between Vue and react
- What are the three ways to define components in react
- How to install and configure the blogging program Typecho on the nginx server
- How to configure load balancing for TCP in nginx server
- How to configure nginx server under Windows system
- How to configure AB to do stress testing for nginx server
- Analysis of location configuration in nginx server
- How to integrate Linux and redmine into the redmine system
- How to build the production environment of nginx + PHP with PHP FPM
- How to optimize the performance of nginx supporting SSL
- How to configure nginx server to prevent flood attack
- [Axios learning] basic use of Axios
- [Axios learning] Axios request mode, concurrent request, global configuration, instance and interceptor
- Use the virtual queue implemented by list to view the first element of the queue in Python without taking it out
- This dependency was not found and to install it, you can run: NPM install score JS
- Front end serial communication
- leedcode. 203 remove linked list elements
- Dialogue with Liu Dayong, information director of Jiuyang shares: key elements of enterprise digital intelligence transformation
- JQuery gets the method summary of parent element, child element and brother element
- Web Security: analysis of DOM XSS vulnerability source code of jquery
- The sales volume of Genesys in China is 283, less than 300, and the domestic sales volume is dismal
- This beast was blessed with skills to test drive the DHT version of Harvard beast
- Bootstrap and jQuery implement tree structure
- Fried cold rice series 5: recursion in JavaScript?
- 2022 open source summer | serverless devs accompany you to "become stronger"
- How to create a high-performance full screen red envelope rain
- Detailed process of spring boot free HTTPS project configuration!
- Create a simple vue3 project
- How to create a simple react project
- Vue custom text background
- Front end HTML
- leetcode:462. Minimum number of moves to make array elements equal II [sort + find the middle]
- City selection (provincial and urban cascade) plug-in v-distpicker component details and a full set of usage
- How to use js to achieve such a drag and zoom effect
- Quick report ~ node JS 18 coming! Let's see what's new
- Easily manage projects using Vue UI graphical interface