如何在不调用函数的情况下使用 Observable.If
How to use Observable.If without calling functions
目前,每个 IF 都会调用函数 isEven 和 isOdd。有没有一种方法只有当IF的计算对应于函数的逻辑路径时才调用函数?
示例:JSBin 的引用:http://jsbin.com/wegesaweti/1/edit?html,js,output)
var isEven = function(x) {
console.log('function isEven called')
return Rx.Observable.return(x + ' is even');
};
var isOdd = function(x) {
console.log('function isOdd called')
return Rx.Observable.return(x + ' is odd');
};
var source = Rx.Observable.range(1,4)
.flatMap((x) => Rx.Observable.if(
function() { return x % 2; },
isOdd(x),
isEven(x)
));
var subscription = source.subscribe(
function (x) {
console.log('Next: ' + x);
});
当前输出:
function isOdd called
function isEven called
Next: 1 is odd
function isOdd called
function isEven called
Next: 2 is even
function isOdd called
function isEven called
Next: 3 is odd
function isOdd called
function isEven called
Next: 4 is even
预期产出
function isOdd called
Next: 1 is odd
function isEven called
Next: 2 is even
function isOdd called
Next: 3 is odd
function isEven called
Next: 4 is even
谢谢!
基于 RXJS docuemntation,thenSource
和 elseSource
需要 Observable
(或 Scheduler
elseSource
)。
您的问题的替代方案:
var source = Rx.Observable.range(1,4).flatMap((x) =>
(x % 2) == 1 ? isOdd(x) : isEven(x)
);
目前,每个 IF 都会调用函数 isEven 和 isOdd。有没有一种方法只有当IF的计算对应于函数的逻辑路径时才调用函数?
示例:JSBin 的引用:http://jsbin.com/wegesaweti/1/edit?html,js,output)
var isEven = function(x) {
console.log('function isEven called')
return Rx.Observable.return(x + ' is even');
};
var isOdd = function(x) {
console.log('function isOdd called')
return Rx.Observable.return(x + ' is odd');
};
var source = Rx.Observable.range(1,4)
.flatMap((x) => Rx.Observable.if(
function() { return x % 2; },
isOdd(x),
isEven(x)
));
var subscription = source.subscribe(
function (x) {
console.log('Next: ' + x);
});
当前输出:
function isOdd called
function isEven called
Next: 1 is odd
function isOdd called
function isEven called
Next: 2 is even
function isOdd called
function isEven called
Next: 3 is odd
function isOdd called
function isEven called
Next: 4 is even
预期产出
function isOdd called
Next: 1 is odd
function isEven called
Next: 2 is even
function isOdd called
Next: 3 is odd
function isEven called
Next: 4 is even
谢谢!
基于 RXJS docuemntation,thenSource
和 elseSource
需要 Observable
(或 Scheduler
elseSource
)。
您的问题的替代方案:
var source = Rx.Observable.range(1,4).flatMap((x) =>
(x % 2) == 1 ? isOdd(x) : isEven(x)
);