Search code examples
rxjsangular5polling

Angular 5 $http polling with RXJS


I'm trying to create a polling service and this is what I have achieved. The goal is to have a polling which can be stopped when response contains a certain value (e.g. running: false)

// Sample call
  _getData(): Observable<any> {
    return new Observable((observer) => {
      setTimeout(() => {
        observer.next({ data: "bar", running: true });
      }, 2000)
    })
  }

  start() {
    timer(0, 5000)
      .pipe(
        concatMap(() => from(this._getData())
        .pipe(map(response => response))
        )
      )
     // .pipe(filter(backendData => backendData.running === true))
      .subscribe(() => console.info("CIAO" + ++calls))
  }

The problem is that this fires once. What am I doing wrong?


Solution

  • This is because concatMap waits until its inner Observable completes.

    In your _getData you return new Observable and then call next() yourself but you never call complete() so the Observable remains opened. Then concatMap will never call its project method again because it's waiting for the previous Observable to complete.