你會想保留源觀察的運行,但如果你讓主事件發生錯誤流將摺疊整個觀察到的,你就不會再收到物品。
解決方案涉及創建一個分離的流,您可以過濾和捕獲,而不會讓上游管道崩潰。
const Rx = require('rxjs/Rx');
function checkValue(n) {
if(n === 4) {
throw new Error("Bad value");
}
return true;
}
const source = Rx.Observable.interval(100).take(10);
source
// pass the item into the projection function of the switchMap operator
.switchMap(x => {
// we create a new stream of just one item
// this stream is created for every item emitted by the source observable
return Observable.of(x)
// now we run the filter
.filter(checkValue)
// we catch the error here within the projection function
// on error this upstream pipe will collapse, but that is ok because it starts within this function and will not effect the source
// the downstream operators will never see the error so they will also not be effect
.catch(err => Rx.Observable.empty());
})
.subscribe(v => console.log(v));
你也可以使用傳遞到抓選擇重啓觀察到的源第二個參數,但是這將啓動它,就好像它沒有之前運行。
const Rx = require('rxjs/Rx');
function checkValue(n) {
if(n === 4) {
throw new Error("Bad value");
}
return true;
}
const source = Rx.Observable.interval(100).take(10);
source.filter(x => checkValue(x))
.catch((err, source) => source)
.subscribe(v => console.log(v));
但是,這並沒有達到預期的效果。您將看到一個重複發射1..3的流,直到時間結束......或者關閉腳本。以先到者爲準。 (這是.retry()
所必需的)
'Observable.if()'似乎已經在v5中被刪除了。 – N13