RxJS 5 Observable:是否有任何结果属于已知集

RxJS 5 Observable: does any result belong to a known set

我在 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')
    );

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

Result: true (because inner observable emits 2, which is found in lookFor

Complete

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

Object {name:"Empty Error", stack:""}

让我的 Observable 在找到匹配项后立即发出 true,但如果在流末尾仍然没有匹配项时发出 false 的正确方法是什么?

还有一个附加参数可让您指定在未找到匹配项时使用的默认值:

...
.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
)
...