Hannes Petri
Hannes Petri

Reputation: 874

RxJS: invoke two async calls, return the first that passes a condition, or a special value of none of them does

Using RxJS, I want to invoke two different asynchronous operations, which may or may not return null. They may also take indefinite time to complete.

I want to achieve the following:

I suppose I can achieve the first two simply as follows:

const bothOperations = merge(callA(), callB());
const firstSuccess = bothOperations.first(res => res !== null);
return firstSuccess;

But how do I get the third possibility into this?

Upvotes: 3

Views: 60

Answers (1)

martin
martin

Reputation: 96959

I think you could do it like this (I'm assuming you're using RxJS 5.5):

merge(callA(), callB())
  .pipe(
    filter(v !== null),
    concat(of(null)),
    take(1),
  )

The take(1) operator makes sure only one value is passed and concat(of(null)) appends null after both source Observables completed.

Just note that if both source Observables run indefinitely than this will never complete. You could add timeout() operator however.

Upvotes: 5

Related Questions