Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS: an interval that starts right away

Tags:

angular

rxjs

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());
like image 624
user133688 Avatar asked Apr 15 '16 08:04

user133688


1 Answers

I think you could try something like this:

    import { interval } from "rxjs";
    import { map, mergeMap, startWith } from "rxjs/operators";

    interval(1000 * 5).pipe(
      startWith(0),
      mergeMap(() => 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.

like image 121
Luka Jacobowitz Avatar answered Oct 09 '22 12:10

Luka Jacobowitz