Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observable polling?

Tags:

angular

I currently have an Observable timer:

private poller(): Observable<PrepareData> {
    return Observable.timer(0, 5000).switchMap(() => this.http.get("/cgi/dashboard.php")).map(res => res.json());
}

I'd like to have it so a get request is done 5 seconds after the last one completed. Any easy way to do this?

like image 343
Charlie Avatar asked Mar 07 '17 20:03

Charlie


People also ask

What is polling in angular?

Polling is a process by which the client continuously request data from the server without any user interaction. It is mainly used to track the long running back-end process status.

What is take in RXJS?

take returns an Observable that emits only the first count values emitted by the source Observable. If the source emits fewer than count values then all of its values are emitted. After that, it completes, regardless if the source completes.

What is of operator in RXJS?

The of Operator is a creation Operator. Creation Operators are functions that create an Observable stream from a source. The of Operator will create an Observable that emits a variable amount of values in sequence, followed by a Completion notification.


1 Answers

I'll add my answer as @Maxime's answer works, but there is actually no need for a subject.

This is done using the .concat() operator and recursion with the getData() function.

.concat()

Concatenates multiple Observables together by sequentially emitting their values, one Observable after the other.

(...)

concat will subscribe to first input Observable and emit all its values, without changing or affecting them in any way. When that Observable completes, it will subscribe to then next Observable passed and, again, emit its values. This will be repeated, until the operator runs out of Observables. When last input Observable completes, concat will complete as well.

(I used the js version in order to make a snippet that works with stack Overflow's tool, but this is the same for typescript):

function someHTTPCall() {
  // well it's a fake http call
  console.log("making the Http request (can take up to 5s)...");
  return Rx.Observable.of("http response !")
    .delay(Math.round(Math.random() * 5000));
}

function getData() {
  return someHTTPCall()
    .concat(Rx.Observable.timer(5000).switchMap(() => getData()));
}

let myObs = getData();

myObs.subscribe((data) => {
  console.log(data,"waiting for 5 seconds before next request");
});
<script src="https://unpkg.com/[email protected]/bundles/Rx.min.js"></script>
like image 62
n00dl3 Avatar answered Nov 11 '22 20:11

n00dl3