RxJS 5 Observable:任何结果都属于已知集合

时间:2016-08-15 01:48:26

标签: typescript observable rxjs5

我在Typescript 1.9中编码并使用RxJS 5。我试图建立一个仅发出一个值的观察点:true如果任何内部Observable<number>的发射都属于固定的数字数组。否则false。这是我的代码:

let lookFor = [2,7]; // Values to look for are known
Observable.from([1,2,3,4,5]) //inner observable emits these dynamic values
    .first( //find first value to meet the requirement below
        (d:number) => lookFor.find(id=>id===d)!==undefined,
        ()=>true //projection function. What to emit when a match is found
    )
    .subscribe(
        res => console.log('Result: ',res),
        err => console.error(err),
        ()  => console.log('Complete')
    );

上面的代码效果很好。它会输出:

  

结果:true(因为内部observable发出2,可在lookFor

中找到      

完整

如果我从Observable.from([8,9])开始,我想获得Result: false,因为与lookFor没有重叠,而是触发了错误处理程序:

  

对象{名称:&#34;空错误&#34;,堆栈:&#34;&#34;}

找到匹配后,我的observable会发出true的正确方法是什么,但如果流末尾仍然没有匹配则发出false

1 个答案:

答案 0 :(得分:1)

如果找不到匹配项,还有一个附加参数可让您指定要使用的默认值:

...
.first( //find first value to meet the requirement below
    (d:number) => lookFor.find(id=>id===d)!==undefined,
    ()=>true, //projection function. What to emit when a match is found
    false //default value to emit if no match is found
)
...