Seeven
Seeven

Reputation: 1079

RxJS Observables: new request depending on previous result

How can I generate new values to an Observable or Subject depending on received values?

Example:

Let's say I have an Observable that emits one random number thanks to a web API.

If it is an even number, I want the Observable to emit another random number using the first one as a seed... and so on until I get an odd value.

Note that I don't know in advance how many requests I'm going to make.

Until now, I managed to do it with "weird", recursive methods, but I feel like there must be a much proper way to do this.

Upvotes: 1

Views: 549

Answers (1)

martin
martin

Reputation: 96891

Seems like you can use expand() for this.

const source$ = /* some API call that returns an Observable */;

source$.pipe(
  expand((previous: number) => previous % 2 === 0 ? source$ : EMPTY),
  takeLast(1),
).subscribe(console.log);

This gives you only the last value (the first odd). If you want to get all the intermediate values as well just remove that takeLast(1).

Live demo: https://stackblitz.com/edit/rxjs-czomtm

Upvotes: 2

Related Questions