当前位置:网站首页>Differences and relations among rxjs map, mergemap and switchmap
Differences and relations among rxjs map, mergemap and switchmap
2022-06-28 18:56:00 【WangZiXi】
map、mergeMap and switchMap yes RxJS The three main operators in , stay SAP Spartacus There are a wide range of usage scenarios in development .
map
map yes Observables The most common operator in . Its function is relatively similar to that of mapping in an array . map Receive from Observable Each value issued , Perform an operation on it and return a Observable( therefore Observable The chain can continue ).
Think of it as a function , It will take the original value and projection . The function applies projections to the values and returns them after conversion .
Let's give you an example . Suppose we have a Observable Array . This array is a Person Set . An object represents everyone , Everyone has their own name and favorite role . We're only interested in getting a list of all the characters .
import {
of } from 'rxjs';
import {
map } from 'rxjs/operators';
const observable = of([
{
name: "Parwinder",
character: "Calcifer"
},
{
name: "Laure",
character: "Alchemist"
},
{
name: "Eliu",
character: "X-Men"
},
{
name: "Robert",
character: "Link"
}
]);
observable.pipe(
map(arr => arr.map(person => person.character)) // loops over objects and returns characters
).subscribe(
char => console.log(char) // ["Calcifer", "Alchemist", "X-Men", "Link"]
);
mergeMap
mergeMap yes Observable map and mege The combination of . In the actual project , Regular needs map Generate multiple Observable. for example , Now I have an array of characters , For each role , I want to make a back-end call and get some information .
See the following example :
import {
of, from } from 'rxjs';
import {
map } from 'rxjs/operators';
const dummyApi = (character) => {
// fake api call function
return of(`API response for character: ${
character}`).pipe(
delay(1000) // the fake api takes 1 second
);
}
from(["Calcifer", "Alchemist", "X-Men", "Link"]) // characters I need to get information for
.pipe(
map(arr => dummyApi(arr)) // generates 4 new Observables
).subscribe( // subscribing Observable (outer) of 4 Observables (inner)
data => data.subscribe(i => console.log(i)) // subscribing to inner Observables
)
dummyApi It is a typical example of a real project : Enter a keyword , Return the details corresponding to the keyword , Wrapped in a Observable In the object . in other words ,map The output of the projection is a Observable, Not the ordinary object , So the above code writes ugly nesting subscribe To get the actual value .
Use mergeMap after , This operator automatically converts map Back to Observable Conduct flatten operation . Use map The ugly double subscribe The call disappeared .
import {
of, from } from 'rxjs';
import {
mergeMap } from 'rxjs/operators';
const dummyApi = (character) => {
return of(`API response for character: ${
character}`)..pipe(
delay(1000)
);
}
from(["Calcifer", "Alchemist", "X-Men", "Link"])
.pipe(
mergeMap(arr => dummyApi(arr)) // gets 4 Observable as API response and merges them
).subscribe( // we subscribe to one mapped and merged Observable
data => console.log(data)
)
switchMap
switchMap With the function of mergeMap The same function , But slightly different . switchMap Will subscribe to external Observable All internal in Observable, But it won't merge internal Observable. It changes to switch to the latest Observable And pass it to the chain .
It still provides a Observable As the output , Not by merging , But by just starting from the latest Observable The idea of sending results .
For our last example , If we use switchMap, We will only start from the last Observable Get results in .
import {
of, from } from 'rxjs';
import {
switchMap, delay } from 'rxjs/operators';
const dummyApi = (character) => {
return of(`API response for character: ${
character}`).pipe(
delay(1000)
);
}
from(["Calcifer", "Alchemist", "X-Men", "Link"])
.pipe(
switchMap(arr => dummyApi(arr))
).subscribe(
data => console.log(data) // API response for character: Link
)
Some scenes are switchMap Good at , For example, the so-called typehead.
Imagine a scene like this :UI There is an input box on the , We're in it based on what the end user enters , Return search results to it .
If the user intends to enter Chase, Start input C, Then trigger a API call . Then the customer continues to enter h, We must aim at Ch Call the background once API. here , We were aiming at C Of API The call is useless . We should cancel the previous Observable, And subscribe to Ch Corresponding Observable. More generally , We need to switch to the latest Observable.
import {
of, from } from 'rxjs';
import {
switchMap, delay } from 'rxjs/operators';
const dummyApi = (character) => {
return of(`Search result for keyword: ${
character}`).pipe(
delay(1000)
);
}
from(["C", "Ch", "Cha", "Chas", "Chase"]) // mimic key input in text field
.pipe(
switchMap(arr => dummyApi(arr))
).subscribe(
data => console.log(data) // Search result for keyword: Chase
)
边栏推荐
猜你喜欢

Seata implementation of sharing JDBC distributed transaction

Memory leak

BioVendor游离轻链(κ和λ)Elisa 试剂盒检测步骤

1 goal, 3 fields, 6 factors and 9 links of digital transformation

打破学科之间壁垒的STEAM教育

Summary of the use of qobjectcleanuphandler in QT

Openharmony - detailed source code of Kernel Object Events

Mindspire series one loading image classification data set

浦发银行软件测试面试真题(小编面试亲测)

Anonymous function this pointing and variable promotion
随机推荐
向上转型和向下转型
ONEFLOW source code parsing: automatic inference of operator signature
双功能交联剂丨Lumiprobe 磺基花青7二羧酸研究
curl: (56) Recv failure: Connection reset by peer
推荐两款超高质量的壁纸软件
[unity3d] emission (raycast) physical ray (Ray)
ANR Application Not Responding
【C#】详解值类型和引用类型区别
实时Transformer:美团在单图像深度估计上的研究
Professor Michael Wooldridge of Oxford University: how the AI community views neural networks in the past 40 years
1 goal, 3 fields, 6 factors and 9 links of digital transformation
Collection of real test questions
MindSpore系列一加载图像分类数据集
电子商务盛行,怎么提高商店转换率?
About Covariance and Correlation(协方差和相关)
Lumiprobe 蛋白质标记研究方案
【Unity3D】相机跟随
devpi
C# 41. int与string互转
模块化操作