有一个websocket连接,如果连接是直立的,我会尝试获取信息。我尝试用RxJS和间隔做。问题是,在一次超时后,流结束,我希望间隔继续,以便我可以看到它是否已经重新连接。
function listenToConnectionLost () {
return rx.Observable
.interval(5000) // every 5 seconds
.flatMap(tryPing)
.distinctUntilChanged()
// so I want to have either "connected" or "timeout" here
// onNext I want to handle the different outputs
;
}
function tryPing () {
var pingPromise = getPingPromise();
var pingObservable = rx.Observable
.fromPromise(pingPromise)
.timeout(5000)
.catch(Rx.Observable.just('timeout')) // catches error, but
// completes the stream
;
return pingObservable;
}
function getPingPromise () {
// returns a promise, which resolves when connection is upright
}
这里我还有一个带有“伪造”间隔的实例:http://jsbin.com/gazuvu/4/edit?js,console
谢谢!
答案 0 :(得分:0)
以上发布的代码正在运行,因为已完成的流将被输入listenToConnectionLost
中的flatMap。我通过将以下代码插入getPingPromise
来测试它。
function getPingPromise () {
if(Math.random() < 0.5) {
return $q.when('connected'); // resolves immediately
}
else {
return $q.defer().promise; // never resolves, triggers timeout
}
}