Reputation: 109
I'm learning Rx and am working through some of the semantics. As an experiment, I'm building an observable timer that calls OnError on the tenth tick. So far, I have 2 methods that I believe exhibit identical behavior:
var timer = Observable.Interval(TimeSpan.FromMilliseconds(200));
// method 1
Observable.Create<long>(
x => timer.Subscribe(tick => {
if (tick == 10)
{
x.OnError(new Exception());
}
x.OnNext(tick);
}));
// method 2
timer.Select(x => {
if (x == 10)
{
throw new Exception();
}
return x;
});
Am I correct in assuming that both of these methods will behave exactly the same? If not, what are the differences?
Upvotes: 0
Views: 186
Reputation: 74654
The 2nd way is not equivalent, throwing in a selector results in Undefined Behavior That Might Happen To Look The Same™. Here's a few more ways:
Observable.Interval(TimeSpan.FromMilliseconds(200))
.Take(9)
.Concat(Observable.Throw<long>(new Exception("Die!")));
Observable.Interval(TimeSpan.FromMilliseconds(200))
.SelectMany(x => {
if (x < 10) return Observable.Return(x);
return Observable.Throw<long>(new Exception("Die!"));
});
Upvotes: 1