[英]Timeout observable subscription without value
我正在訂閱Firebase的可觀察到的返回值。 如果連接斷開,我希望訂閱超時。 正確的做法是什么? 我嘗試了以下操作,但是在收到最后一個值后20秒超時:
let chatSubscription = this.getChats().timeoutWith(20000, Observable.throw(new Error('timeout'))).subscribe(chats => { ... });
//編輯:getChats()
getChats() {
return Observable.create(observer => {
let chatList = this.db.list('/users/' + this.auth.user.uid + '/chats').timeoutWith(20000, Observable.throw(new Error('timeout'))).subscribe(chats => {
observer.next(chats);
});
//keep track of this subscription
this.openSubscriptions.push(chatList);
});
}
你可以用一個超時開始Observable
和switchMap
在第一次發出的項目,比如從最初的超時你原來值:
const chats$ = this.getChats();
chats$.map(v => Observable.just(v))
.startWith(Observable.never().timeoutWith(20000, new Error()))
.switchMap(v => v)
.subscribe(...);
如果在初始化的20 switchMap
內發出了一個值,則switchMap
只是身份運算符,並繼續提供原始值流中的項。
您可以使用race
來監聽首先可觀察到的東西:
const chats = this.db.list('/users/' + this.auth.user.uid + '/chats');
const timeout = Observable.throw(new Error("timed out")).delay(20000);
const chatWithTimeout = Observable.race(chats, timeout);
chatWithTimeout.subscribe(msg => ..., err => ...);
另外,您對Observable.create
的使用似乎有些不合常規。 我建議采取以上代碼並將其用作您的getChats
:
getChats() {
const chats = this.db.list('/users/' + this.auth.user.uid + '/chats');
const timeout = Observable.throw(new Error("timed out")) .delay(20000);
const chatWithTimeout = Observable.race(chats, timeout);
return chatWithTimeout;
}
// usage
const subscription = foo.getChats().subscribe(...);
使用此版本,您無需保留打開的訂閱列表。 讓觀察者自己跟蹤此訂閱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.