0

I make several sequential requests and the result of anotherRequest is used in the second mergeMap-clause. This basically works fine.

My question is: How can I repeat anotherRequest until some condition is met and only pass the approved return-value to the second mergeMap-clause?

someRequest().pipe(
  mergeMap((info) => {
    this.appService.petitionId$.next(Number(lastInfo.petitionId));
    return anotherRequest();
  }),
  mergeMap(
    ...
  ),
);
kellermat
  • 2,859
  • 2
  • 4
  • 21
Alexandra
  • 37
  • 7
  • you can use retry(), https://stackoverflow.com/questions/63113192/how-to-retry-a-subscription-when-it-fails-in-angular-9 – Trouble Jan 27 '23 at 18:52
  • Retry() repeats request if it was error, doesn’t it? I need to check condition if it is true, tnen pass result to MetgeMap – Alexandra Jan 27 '23 at 20:02

1 Answers1

3

You could use expand in combination with filter and take(1). By using the expand-operator the call will be repeated until a given condition is met. filter will make sure that an emission will only be made if the condition was met. And take(1) will trigger an unsubscribe after the first successful emission.

Here you can find my stackblitz example

What's more, you can find the crucial part of my code below:

this.someRequest()
  .pipe(
    mergeMap((info) => {
      return this.anotherRequest().pipe(
        expand((data) =>
          this.isConditionMet(data) ? of(data) : this.anotherRequest()
        ),
        filter((data) => this.isConditionMet(data)),
        take(1)
      );
    }),
    mergeMap((res) => {
      ...
    })
  )
kellermat
  • 2,859
  • 2
  • 4
  • 21