Ugur Korfali
Ugur Korfali

Reputation: 148

Conditionally merge two streams with RxJs

I have two server calls to made to get some response in my stream. But if the first call returns with some data I don't want to execute the second call. I couldn't find a proper operator or a combination of operators to do the cancelation (I don't want to throw an error btw) of the second request on the success of the first one.

I also tried defaultIfEmpty but looked like a hack and I didn't like it.

I created a StackBlitz example you can check it here but I am not sure it is a good practice or not. So basically I need a conditional concatMap.

If you know how to do it with available operators without creating a new one, I really like to hear your approaches.

Thanks in advance.

Upvotes: 1

Views: 2069

Answers (2)

Mark van Straten
Mark van Straten

Reputation: 9425

If your first async request is of type Observable<T> and only returns a value T on success and otherwise just completes without emitting a value you can use a simple .concat() instead:

firstAsyncCall()
  .concat(secondAsyncCall())
  .take(1)

The .take(1) will make sure the secondAsyncCall() will not be invoked if the firstAsyncCall returns (at least) 1 value.

Upvotes: 3

user4676340
user4676340

Reputation:

Use filter to stop the stream when the value doesn't suit you :

https://stackblitz.com/edit/typescript-1uvrgf?file=index.ts

const interval$ = interval(100);

interval$.pipe(
  filter(val => val % 10 === 0),
  take(10),
).subscribe(val => console.log(val));

Upvotes: 0

Related Questions