[英]Angular 5 RxJs concatMap,switchMap,mergeMap which?
I have this method to get token via localstorage, if token is not exist or is expired, I will call API to get another token and store to localstorage.我有这种通过localstorage获取令牌的方法,如果令牌不存在或已过期,我将调用API来获取另一个令牌并存储到localstorage。
In this case, which map should I use, currently using mergeMap, or other way to do this?在这种情况下,我应该使用哪个地图,目前使用的是 mergeMap,还是其他方式来做到这一点?
public doGetToken():Observable<Token> {
return this.loadToken().pipe( //get via localstorage
map(token=>{
let valid = this.validateTokenIsValid(token);
let data = {
token: token,
valid: valid
};
return data;
}),
mergeMap(data=>{
if (!data.valid) {
return this.doApiGetToken(data.token).pipe(
map(
token=>{
this.saveToken(token); //save to localstorage
return token;
}
)
);
} else {
return of(data.token);
}
})
);
version: Angular 5, rxjs5版本:Angular 5,rxjs5
Thank you in advance.先感谢您。
If you only make one request , then it doesn't matter which map you use.如果您只提出一个请求,那么您使用哪张地图都没有关系。
mergeMap (also called flatMap), concatMap , exhaustMap or switchMap will behave the same. mergeMap(也称为 flatMap)、concatMap、exhaustMap 或 switchMap 的行为相同。
These operators behave differently when you emit more than 1 value:当您发出 1 个以上的值时,这些运算符的行为会有所不同:
switchMap切换映射
will apply the mapping to the latest input received:将映射应用于收到的最新输入:
Src : -----A----B----C--D-E-------
switchMap (x => x--x) // emit x twice when received
Out: ------A--A-B--B-C-D-E--E----
concatMap连接映射
will finish the mapping before taking another input:将在接受另一个输入之前完成映射:
Src : -----A----B----C--D-E-----------
concatMap (x => x--x) // emit x twice when received
Out: ------A--A-B--B-C--C--D--D-E--E
mergeMap合并映射
is like concatMap, but it doesn't wait for mapping to complete.就像 concatMap,但它不等待映射完成。 The results can overlap though:
结果可能会重叠:
Src : -----A----B----C-D---E-----------
mergeMap (x => x--x) // emit x twice when received
Out: ------A--A-B--B-C-D-C-D-E--E-----
exhaustMap排气图
is like a reversed switchMap, it gives priority to the output:就像一个反向的switchMap,它优先输出:
Src : -----A--------B----C-D---E-----------
exhaustMap (x => x--x--x) // emit x thrice when received
Out: ------A--A--A--B--B--B-D--D--D-------
For more information :想要查询更多的信息 :
https://medium.com/@vdsabev/the-simple-difference-between-rxjs-switchmap-and-mergemap-397c311552a5 https://medium.com/@vdsabev/the-simple-difference-between-rxjs-switchmap-and-mergemap-397c311552a5
Marble diagrams :大理石图:
http://rxmarbles.com/#mergeMap http://rxmarbles.com/#mergeMap
Edit : I moved the simplification of your code to the bottom to make the general information visible at first sight.编辑:我将您的代码的简化移到底部,以使一般信息一目了然。
public doGetToken(): Observable<Token> {
return this.loadToken()
.pipe( //get via localstorage
mergeMap(token => {
if(!this.validateTokenIsValid(token))
return of(token)
return this.doApiGetToken(token)
.pipe(
tap( token => this.saveToken(token)) //save to localstorage
);
})
)
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.