Matthew Thompson
Matthew Thompson

Reputation: 33

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?

Upvotes: 3

Views: 804

Answers (1)

Jota.Toledo
Jota.Toledo

Reputation: 28434

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$));
}

Upvotes: 2

Related Questions