3

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?

1 Answer 1

2

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$));
}
Sign up to request clarification or add additional context in comments.

1 Comment

That was it, the key was to use startWith(null) to force the first emission

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.