RxJS 5可观察:是否有任何结果属于已知集合

RxJS 5可观察:是否有任何结果属于已知集合

问题描述:

我正在编码Typescript 1.9并使用RxJS 5。我试图构建一个只能发射一个值的可观测值:true如果任何内部的Observable<number>的发射属于固定的数字阵列。否则为false。这是我的代码:RxJS 5可观察:是否有任何结果属于已知集合

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

上面的代码很好用。它将输出继电器:

结果:真实的(因为内部观察到发射2,这是在lookFor

完全发现

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

Object {name:“Empty E RROR”,栈:‘’}

什么让我观察到的要尽快找到一个匹配发出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 
) 
...