RxJS: interval that starts immediately

I am making a simple angular2 toy project that hits a URL every 5 seconds. Right now I have it so that it polls the URL, and when the document loads, it does not wait. But that seems really awkward. Is there a more elegant solution?

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()); 
+5
source share
2 answers

Instead of timer you can use

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

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

+2
source

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 instantly produce a value, and then once every 5 seconds.

Check out the documentation here.

+5
source

Source: https://habr.com/ru/post/1247191/


All Articles