Rx.Observable.if(condition, thenSource, [elseSource])
给出一个或两个流,判断Observable应该取哪个流的值。(相当于 if...else)
参数
condition
(Function
): 判决条件,为true
则取thenSource
, 否则执行elseSource
.thenSource
(Observable
): Observable, 当condition
为true
时执行。[elseSource]
(Observable|Scheduler): Observable, 当condition
为false
时执行。如果没有提供,则默认为Rx.Observabe.Empty
.
返回值
(Observable
): Observable
例
This uses and only then source
// 只传入 then source
var shouldRun = true;
var source = Rx.Observable.if(
function () { return shouldRun; },
Rx.Observable.return(42)
);
var subscription = source.subscribe(
function (x) {
console.log('Next: ' + x);
},
function (err) {
console.log('Error: ' + err);
},
function () {
console.log('Completed');
});
// => Next: 42
// => Completed
The next example uses an elseSource
// 设置 elseSource
var shouldRun = false;
var source = Rx.Observable.if(
function () { return shouldRun; },
Rx.Observable.return(42),
Rx.Observable.return(56)
);
var subscription = source.subscribe(
function (x) {
console.log('Next: ' + x);
},
function (err) {
console.log('Error: ' + err);
},
function () {
console.log('Completed');
});
// => Next: 56
// => Completed