[Fixed] RxJS: an interval that starts right away


I’m making a simple toy angular2 project that hits an url every 5 seconds. Right now I have it so that it polls the url, and when the the document loads it doesn’t wait. But it seems really clunky. Is there a better more elegant solution to this?

Observable.interval(1000 * 5)
      .flatMap(() => this.http.get(url))
      .merge(this.http.get(url)) // Merges a stream that starts right away!!!
      .map((res:Response) => res.json());


You can use timer instead

Observable.timer(0, 1000 * 5)
          .flatMap(() => this.http.get(url),
                   (_, res) => res.json);

timer takes an initial delay before emitting its first event, and then emits just like interval every 5 seconds.

Leave a Reply

(*) Required, Your email will not be published