I ran into my own issues interpreting how this (and onErrorResumeNext
) functioned. The struggle I encountered was with what context the catch (or resume next) applied to. The simple colloquial translation that makes sense for me is the following:
Given a stream (or observable) of observables, catch
(or onErrorResumeNext
) will consume the error and allow you to provide one or more observables to continue the original stream with.
The key take away is that your original source is interrupted and replaced with the observable(s) you provide in the catch
/onErrorResumeNext
function. This means that if you had something like this:
var src = Rx.Observable
.interval(500)
.take(10)
.select(function(x) {
if (x == 5) {
return Rx.Observable.throw('Simulated Failure');
}
return Rx.Observable.return(x * 2);
})
Then adding .catch(Rx.Observable.return('N/A'))
or .onErrorResumeNext(Rx.Observable.return('N/A'))
will not actually just continue your stream (sourced by the interval
), but rather end the stream with a final observable (the N/A
).
If you are looking to instead handle the failure gracefully and continue the original stream you need to so something more like .select(function(x) { return x.catch(Rx.Observable.return('N/A')); })
. Now your stream will replace any observable element in the stream that fails with a caught default and then continue on with the existing source stream.
var src = Rx.Observable
.interval(500)
.take(10)
.select(function(x) {
if (x == 5) {
return Rx.Observable.throw('Simulated Failure');
}
return Rx.Observable.return(x * 2);
})
//.catch(Rx.Observable.return('N/A'))
//.onErrorResumeNext(Rx.Observable.return('N/A'))
.select(function(x) { return x.catch(Rx.Observable.return('N/A')); })
.selectMany(function(x) { return x; });
var sub = src.subscribe(
function (x) { console.log(x); },
function (x) { console.log(x); },
function () { console.log('DONE'); }
);
// OUTPUT:
// 0
// 2
// 4
// 6
// 8
// N/A
// 12
// 14
// 16
// 18
// DONE
Here is a JSFiddle that shows this in action.
when
andthen
? It doesn't look like it's buying you anything... – Speculum