Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular / RxJS: Sending an API request then polling another endpoint

I want to send an API request then poll another endpoint until a response with a success: true body comes back from the second endpoint. I am using Angular's HTTPClient to make my requests. My original thought was to do this:

createConversion(request): Observable<any> {
    return this.http.post('/endpoint', request).pipe(

      // This is the problem: I want to start polling before this post() call emits

      mergeMap((response) => {

        // Start polling

        return timer(0, 5000).pipe(
          takeUntil(this.converted$),
          concatMap(() => {

            return this.http.get('/second-endpoint')
          })
        )
      })
    );

However, the mergeMap is not called until the first post() call emits with the first request's response. Is there an RxJS operator that will allow me to start the polling before the first post() call emits?

like image 745
Matthew Thompson Avatar asked Apr 08 '26 23:04

Matthew Thompson


1 Answers

Try with:

createConversion(request): Observable<any> {
    const post$ = this.http.post('/endpoint', request).pipe(startWith(null)); 
    // force fake emission
    const get$ = this.http.get('/second-endpoint');
    const polling$ = timer(0,5000).pipe(mergeMap(_=> get$), takeUntil(this.converted$));

    return post$.pipe(mergeMap(_=> polling$));
}
like image 146
Jota.Toledo Avatar answered Apr 11 '26 18:04

Jota.Toledo



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!