我有这个工作代码:
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)
})
Run Code Online (Sandbox Code Playgroud)
这是一个正在运行的 Stackblitz。
预期输出为:
output 0
output 2
output 6
output 9
Run Code Online (Sandbox Code Playgroud)
只有一个问题。这行代码非常冗长:
mergeMap(x => iif(() => x <= 1, of(x).pipe(double()), of(x).pipe(triple())))
Run Code Online (Sandbox Code Playgroud)
是否可以简化这条线?
您可以简单地使它们起作用并使用:而不是创建double和自定义运算符:triplemap
const double = (x: number) => x * 2;
const triple = (x: number) => x * 3;
timer(0, 1000).pipe(
take(4),
map(x => (x <= 1 ? double(x) : triple(x)))
);
Run Code Online (Sandbox Code Playgroud)
如果修改来自可观察源,则可以使用返回可观察值的函数来代替mergeMap:
const double$ = (x: number) => of(x * 2);
const triple$ = (x: number) => of(x * 3);
timer(0, 1000).pipe(
take(4),
mergeMap(x => x <= 1 ? double$(x) : triple$(x))
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
112 次 |
| 最近记录: |