I have a behavior subject
var source = new BehaviorSubject<int>(0);
I then process that source with something like
var withErrors = source
.Select(v =>
{
if (v == 2)
{
throw new Exception("Ouch ");
}
return v;
})
I want to subscribe to withErrors in such a way that I can skip the errors. An attempt with catch like this.
public IObservabe<int> SkipError(IObservable<T> source){
return source
.Catch(e=>SkipErrors(source.Skip(1));
}
and then call it thus
var withoutErrors = SkipError(withErrors);
the Skip is an attempt to avoid repeating the last error on the behaviour subject but alas it doesn't work that way. Skip doesn't skip over errors but only over valid data so the error from the current state in the behavior subject keeps getting through.
Is there a clever way of writing Skip that will also skip over errors. Something tells me this is not possible but hopefully I'm wrong
As the premise of the question is wrong I present a better
way to do this using the Exceptional<T>
monad. For example
IObservable<int> source = ....;
IObservable<Exceptional<string>> withErrors =
source.Select(i=>Exceptional.Execute(()=>{
if(v==2){
throw new Exception("Ouch");
}
return v.ToString();
});
IObservable<Exception> errors =
withErrors.Where(v=>v.HasException).select(v=>v.Exception);
IObservable<string> values =
withErrors.Where(v=>!v.HasException).select(v=>v.Value);
and just for fun you can do
Exceptional<string> r =
from x in Exceptional.Execute(() => "xxx")
from y in Exceptional.Execute(() => "zzz")
select x + y;
which will generation an Exceptional holding the value "xxxzzz". If any of the steps does throw an exception then it will short circuit and hold only the Exception.
My implementation based off another SO answer is https://gist.github.com/bradphelan/6154972
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With