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());

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

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.

Jason
Guest

I think you could try something like this:

    Observable.interval(1000 * 5)
      .startWith(0)
      .flatMap(() => this.http.get(url))
      .map((res:Response) => res.json());

This will emit a value immediatly and then once every 5 seconds.

Check out the documentation here.