Reputation: 43474
Recently I become aware that the Rx Finally
operator behaves in a way which, at least for me, is unexpected. My expectation was that any error thrown by the finallyAction
would be propagated to the operator's observers downstream. Alas this is not what happens. In the reality the operator first propagates the completion (or the failure) of the antecedent sequence to its observers, and then invokes the action
, at a point in time when it's not possible to propagate a potential error thrown by the action. So it throws the error on the ThreadPool
, and crashes the process. Which is not only unexpected, but also highly problematic. Below is a minimal demonstration of this behavior:
Observable
.Timer(TimeSpan.FromMilliseconds(100))
.Finally(() => throw new ApplicationException("Oops!"))
.Subscribe(_ => { }, ex => Console.WriteLine(ex.Message),
() => Console.WriteLine("Completed"));
Thread.Sleep(1000);
Outcome: Unhandled exception (Fiddle)
The exception thrown by the Finally
lambda is not handled by the Subscribe
:onError
handler, as it would be desirable.
This feature (I am tempted to call it a flaw) limits severely the usefulness of the Finally
operator in my eyes. Essentially I can only use it when I want to invoke an action that is expected to never fail, and if it fails it would indicate a catastrophic corruption of the application's state, when no recovery is possible. I could use it for example to Release
a SemaphoreSlim
(like I've done here for example), which can only fail if my code has a bug. I am OK with my app crashing in this case. But I've also used it recently to invoke an unknown action supplied by the caller, an action that could potentially fail, and crashing the app in this case is unacceptable. Instead, the error should be propagated downstream. So what I am asking here is how to implement a Finally
variant (let's call it FinallySafe
) with identical signature, and the behavior specified below:
public static IObservable<TSource> FinallySafe<TSource>(
this IObservable<TSource> source, Action finallyAction);
finallyAction
should be invoked after the source
sequence has emitted an OnCompleted
or an OnError
notification, but before this notification is propagated to the observer.finallyAction
invocation completed successfully, the original OnCompleted
/OnError
notification should be propagated to the observer.finallyAction
invocation failed, an OnError
notification should be propagated to the observer, containing the error that just occurred. In this case the previous error, the one that may have caused the source
to complete with failure, should be ignored (not propagated).finallyAction
should also be invoked when the FinallySafe
is unsubscribed before the completion of the source
. When a subscriber (observer) disposes a subscription, the finallyAction
should by invoked synchronously, and any error should be propagated to the caller of the Dispose
method.FinallySafe
is subscribed by multiple observers, the finallyAction
should be invoked once per subscription, independently for each subscriber, following the rules above. Concurrent invocations are OK.finallyAction
should never be invoked more than once per subscriber.Validation: replacing the Finally
with the FinallySafe
in the code snippet above, should result to a program that doesn't crash with an unhandled exception.
Alternative: I am also willing to accept an answer that provides a reasonable explanation about why the behavior of the built-in Finally
operator is better than the behavior of the custom FinallySafe
operator, as specified above.
Upvotes: 1
Views: 479
Reputation: 43474
Here is an implementation of the FinallySafe
operator, having the behavior specified in the question:
/// <summary>
/// Invokes a specified action after the source observable sequence terminates
/// successfully or exceptionally. The action is invoked before the propagation
/// of the source's completion, and any exception thrown by the action is
/// propagated to the observer. The action is also invoked if the observer
/// is unsubscribed before the termination of the source sequence.
/// </summary>
public static IObservable<T> FinallySafe<T>(this IObservable<T> source,
Action finallyAction)
{
return Observable.Create<T>(observer =>
{
var finallyOnce = Disposable.Create(finallyAction);
var subscription = source.Subscribe(observer.OnNext, error =>
{
try { finallyOnce.Dispose(); }
catch (Exception ex) { observer.OnError(ex); return; }
observer.OnError(error);
}, () =>
{
try { finallyOnce.Dispose(); }
catch (Exception ex) { observer.OnError(ex); return; }
observer.OnCompleted();
});
return new CompositeDisposable(subscription, finallyOnce);
});
}
The finallyAction
is assigned as the Dispose
action of a Disposable.Create
disposable instance, in order to ensure that the action will be invoked at most once. This disposable is then combined with the disposable subscription of the source
, by using a CompositeDisposable
instance.
As a side note, I would like to address the question if we could go even further, and propagate downstream a possible error of the finallyAction
during the unsubscription. This could be desirable in some cases, but unfortunately it's not possible. First and foremost doing so would violate a guideline, found in The Observable Contract document, that states:
When an observer issues an Unsubscribe notification to an Observable, the Observable will attempt to stop issuing notifications to the observer. It is not guaranteed, however, that the Observable will issue no notifications to the observer after an observer issues it an Unsubscribe notification.
So such an implementation would be non-conforming. Even worse, the Observable.Create
method enforces this guideline, by muting the observer
immediately after the subscription is disposed. It does so by encapsulating the observer inside an AutoDetachObserver
wrapper. And even if we tried to circumvent this limitation by implementing an IObservable<T>
type from scratch, any built-in operator that could be attached after our non-conforming Finally
operator would mute our post-unsubscription OnError
notification anyway. So it's just not possible. An error during the unsubscription cannot be propagated to the subscriber that just requested to unsubscribe.
Upvotes: 1
Reputation: 7835
I read the documentation and now I'm sure. The finally
-operator will be called after the completition and should not throw any exception.
Compared to non-reactive programming:
StreamReader file = new StreamReader("file.txt");
string ln;
try {
while ((ln = file.ReadLine()) != null) {
Console.WriteLine(ln);
}
}
finally {
// avoid to throw an exception inside of finally!
if (file != null) {
file.close();
}
}
It is important to not throw an exception inside of finally
.
Here is an example howto use it correctly (fiddle):
using System;
using System.Reactive.Linq;
using System.Threading;
public class Program
{
public static void Main()
{
Observable
.Range(1,5) // simulates stream-reader
.Finally(() => Console.WriteLine("Close streamreader"))
.Do(i => {
if (i == 5) {
throw new ApplicationException("Oops!"); // simulates IO-error
}
Console.WriteLine("Read " + i);
})
.Subscribe(_ => { }, ex => Console.WriteLine(ex.Message),
() => Console.WriteLine("Completed"));
Thread.Sleep(1000);
}
}
I'm not sure what you are trying to do (and I'm pretty new to c# reactive), but I think you are using not the right operator.
But you can patch it, if you want. In this article, they do something familar.
http://introtorx.com/Content/v1.0.10621.0/11_AdvancedErrorHandling.html
Upvotes: 0
Reputation: 117047
Finally
gets called after the sequence has ended, and since the Rx contract only allows one OnError
or OnCompleted
it can't issue a second one.
But, if you replace the Finally
with Do
you can get the behaviour that you want.
Try this code:
Observable
.Timer(TimeSpan.FromMilliseconds(100))
.Do(_ => { }, () => throw new ApplicationException("Oops!"))
.Subscribe
(_ => { },
ex => Console.WriteLine(ex.Message),
() => Console.WriteLine("Completed"));
Thread.Sleep(TimeSpan.FromMilliseconds(1000));
That operates as you expect it to.
I get this output:
Oops!
If you want to run something at unsubscribe, then use this extension method:
public static class Ext
{
public static IObservable<T> Unsubscribed<T>(this IObservable<T> source, Action unsubscribed) =>
Observable.Create<T>(o =>
new CompositeDisposable(source.Subscribe(o), Disposable.Create(unsubscribed)));
}
Here's an example of its use:
var source = Observable.Never<int>();
var subscription =
source
.Unsubscribed(() => Console.WriteLine("Unsubscribed"))
.Subscribe();
subscription.Dispose();
That outputs:
Unsubscribed
Upvotes: 2