Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RXJS - multiple consecutive http requests

source<http>
  .pipe(
    switchMap(d => this.http.get(d))
      .pipe(
        switchMap(j => this.http.get(j))
      )
  )
  .subscribe()

Hello, I need to make 3 http requests consecutively where each call contains data for the next call.. are nested switch maps the best practice for this case?

like image 636
s1eeper Avatar asked Nov 29 '25 20:11

s1eeper


2 Answers

You don't need to nest them. You can simply chain them:

source<http>
  .pipe(
    switchMap(d => this.http.get(d)),
    switchMap(j => this.http.get(j))
  )
  .subscribe()

Apart from that, using multiple switchMap is the way to go.

like image 155
pascalpuetz Avatar answered Dec 01 '25 12:12

pascalpuetz


switchMap is better option for consecutive calls.

    const first$: Observable<string> = of('first').pipe(tap(c => console.log(c)));
    const second$: Observable<string> = first$.pipe(
      switchMap(first=> {
        return of(first+ ' ' + 'second');
      })
    );
    const third$: Observable<string> = combineLatest(first$, second$).pipe(
      switchMap(([first, second]) => {
        return of(first + second + 'third');
      })
    );

    combineLatest(first$, second$, third$).subscribe(() => {});
like image 30
rkparmar Avatar answered Dec 01 '25 11:12

rkparmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!