[英]RXJS RetryWhen - continue error downstream while attempting retry
步驟:
我有一個源流(可觀察的),它是一個網絡套接字連接。
當連接斷開或錯誤時,源會在流上發出錯誤。
在源的下游,我使用retryWhen
每隔 x 秒嘗試重新連接到 Web 套接字連接。
在下游,我有一個設置默認值的catchError
。 這允許應用程序知道連接的最新狀態。
示例代碼(我的代碼的一個非常簡單的示例):
connect(): Observable<any> {
return this.websocket() // source stream that errors when it disconnects
.pipe(
retryWhen( errors =>
errors.pipe(
delay( 2000 ) // delay retry
)
)
)
}
connectionStatus(): Observable<boolean>{
return this.connect().pipe(
catchError( () => of( false ) ), // this does not trigger with the retryWhen
map( () => true )
)
}
問題:
我希望下游訂閱者在嘗試retryWhen
時知道它已斷開連接。 但是,在retryWhen
發生時不會觸發下游catchError
。
我如何嘗試為所有訂閱者重新連接(不僅僅是 connectionStatus),以及在連接斷開時通知下游(錯誤)的任何想法。
重新連接后,我想繼續向所有訂閱者流式傳輸,就像什么也沒發生一樣。
如果有任何不清楚的地方,請告訴我。
所以寫這篇文章幫助我回答了我自己的問題。
/*
Basic stream handling no errors or retries..
*/
connect(){
return this.websocket();
}
/*
Have a stream that is always connected for all subscribers
*/
alwaysConnected(){
return this.connect().pipe(
retryWhen( errors => {
return errors.pipe(
delay( 2000 )
)
})
)
}
/*
use the continuous stream (no errors) and then in sub stream listen for the errors.
*/
connectionFails() {
return this.alwaysConnected().pipe(
switchMap( () => {
return this.connect().pipe( // switch to stream that errors
catchError( error => of( false ) ),
filter(connection => connection === false )
)
})
)
}
/*
Get a boolean for either a fail or success
*/
connectionStatus() {
return merge(
this.connectionFails(),
this.alwaysConnected().pipe( map( () => true ))
)
}
有幾個問題。
處理重試和捕獲錯誤
處理錯誤時未完成訂閱
可能有一個更簡單更優雅的解決方案。 隨意建議。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.