可观察的轮询? [英] 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());
}
我想拥有它,因此在完成最后一个请求后5秒钟完成了一个get请求.有什么简单的方法吗?
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?
推荐答案
这是一个有趣的问题,我很高兴提出解决方案.
This is an interesting question and I had some fun to come up with a solution.
此解决方案如您期望的那样等待上一个完成:
const { Observable, Subject } = Rx
const getFakeHttpRequest$ = () => Observable.of('response !').delay(3000)
const polling$ = new Subject()
Observable
// need to tick the first time
.of(null)
// everytime our polling$ subject will emit, we'll do again what's next
.merge(polling$)
// register to a fake request
.switchMap(_ =>
getFakeHttpRequest$()
.do(_ => {
// once we're here, the request is done
// no mater how long it was to get a response ...
console.log('HTTP request done !');
// ... we wait 5s and then send a new value to polling$ subject
// in order to trigger a new request
setTimeout(_ => polling$.next(null), 5000)
})
)
.subscribe()
请注意,我已将请求延迟3秒,并且每8秒就会启动一个新请求,因为我们等待3秒才能得到答复,然后按照您的问题的要求等待5秒.
Notice that I've put a 3s delay on the request, and that a new request kicks in every 8s, as we waited 3s for the response and then 5s as requested in your question.
这是一个正在工作的Plunkr: https://plnkr.co/edit/kXefUbPleqyyUOlfwGuO?p=info
Here's a working Plunkr : https://plnkr.co/edit/kXefUbPleqyyUOlfwGuO?p=info
这篇关于可观察的轮询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文