Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
534 views
in Technique[技术] by (71.8m points)

angular - Observable polling?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...