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:
- If operation A returns value 1, then immediately return value 1
- If operation B returns value 2, then immediately return value 2
- If both operation A and B return
null
, then returnnull
.
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?
I think you could do it like this (I'm assuming you're using RxJS 5.5):
The
take(1)
operator makes sure only one value is passed andconcat(of(null))
appendsnull
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.