Danny
Danny

Reputation: 692

RxJS delay switchMap new observable execution

In my Angular project I'm making some HttpClient call and after response I need to check it's body and execute another HttpClient call or not, depending on first response. Also I need to delay some time the execution of second HttpClient call.

I can do it using switchMap operator but I would like to know how to delay the second http call in correct way.

Here is some very simple example:

export class AppComponent  {
  ngOnInit() {
    this.execute().subscribe(r => console.log(r))
  }

  execute(): Observable<string> {
    return this.http1Call().pipe(switchMap((r) => {
     // Checking if 2d http call must be executed or not
      if (r === '1st call') {
        console.log('---Invalid 1st call, executing 2d')
        // TODO: Is that correct way to execute http2Call with delay ???
        return of({}).pipe(delay(3000), switchMap(() => this.http2Call()))
      }

      return of(r);
    }));
  }

  http1Call(): Observable<string> {
    return of('1st call').pipe(delay(1000));
  }

  http2Call(): Observable<string> {
    console.log('------Inside http2Call')
    return of('--------2d call response').pipe(delay(3000));
  }
}

Upvotes: 1

Views: 3720

Answers (1)

martin
martin

Reputation: 96891

What you have is basically all right you can just simplify (or maybe make more obvious) the part where you make the delay:

return timer(3000).pipe(switchMapTo(this.http2Call()))

timer() with one parameter will emit just once after the delay. You might also use concatMap/concatMapTo instead of switchMap/switchMapTo because in this case you'll never switch anything (timer emits just once and then complete).

Upvotes: 3

Related Questions