簡體   English   中英

超時可觀察到的訂閱沒有價值

[英]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);  
        });
    }

你可以用一個超時開始ObservableswitchMap在第一次發出的項目,比如從最初的超時你原來值:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM