RXJS条件操作员简化
我有此工作代码:
import { timer, take, pipe, map, mergeMap, iif, of } from 'rxjs'
const double = () => {
return pipe(
map((x: number) => x * 2)
)
}
const triple = () => {
return pipe(
map((x: number) => x * 3)
)
}
timer(0, 1000).pipe(
take(4),
mergeMap(x => iif(() => x <= 1, of(x).pipe(double()), of(x).pipe(triple())))
).subscribe(x => {
console.log('output', x)
})
这是工作stackblitz 。
按预期的输出是:
output 0
output 2
output 6
output 9
只有一个问题。这条线很冗长:
mergeMap(x => iif(() => x <= 1, of(x).pipe(double()), of(x).pipe(triple())))
可以简化这条线吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
与其进行
double
和triple
自定义操作员,您可以简单地使其功能,只需使用map
:如果修改来自可观察的源,您可以使用
Mergemap
:stackblitz
Instead of making
double
andtriple
custom operators, you could simply make them functions and just usemap
:If the modifications come from an observable source, you can use a function that returns an observable instead with
mergeMap
:StackBlitz
它可以进一步归结为
It can be further boiled down to this