我认为Rx.Observable.prototype.reduce
就像Array.prototype.reduce
所以我这样写代码
function fn(prev, num){
return Rx.Observable.of(prev+num);
}
fn(1, 1).switchMap(res =>fn(res, 2))
.switchMap(res =>fn(res, 3))
.subscribe(x=>console.log(x));
// 7
Rx.Observable.from([2,3]).reduce(
(prev, cur) =>prev.switchMap(res => fn(res, cur)),
fn(1, 1)
).subscribe(x=>console.log(x))
// SwitchObservable {source: FlatMapObservable}
我想知道为什么我不能以这种方式使用扫描?如何正确使用 Operator?
最佳答案
这是因为你的累加器是一个 Observable。您可以通过再次调用 switchMap 来获取您的值:
Rx.Observable.from([2,3]).scan(
(prev, cur) =>prev.switchMap(res => fn(res, cur)),
fn(1, 1)
).last().switchMap(x => x).subscribe(x=>console.log(x))
编辑后
Rx.Observable.from([2,3]).reduce(
(prev, cur) =>prev.switchMap(res => fn(res, cur)),
fn(1, 1)
).switchMap(x => x).subscribe(x=>console.log(x))
关于javascript - 为什么reduce的行为与手写的链式方法不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41279031/