BeetleJuice BeetleJuice - 3 months ago 21
TypeScript Question

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

I'm coding in

Typescript 1.9
and using
RxJS 5
. I'm trying to build an observable that will emit just one value:
true
if any of the inner
Observable<number>
's emissions belong to a fixed array of numbers.
false
otherwise. This is my code:

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


The code above works great. It will ouput:


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


Complete


If I start with
Observable.from([8,9])
I would like to get
Result: false
since there is no overlap with
lookFor
, but instead the error handler is triggered:


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


What's the right approach to get my observable to emit
true
as soon as a match is found, but to emit
false
if there is still no match at the end of the stream?

Answer

There is an additional parameter that lets you specify the default value to use if no match is found:

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