R3 icon indicating copy to clipboard operation
R3 copied to clipboard

OnErrorResumeAsFailure does not work on SubscribeAwait

Open lxymahatma opened this issue 9 months ago • 0 comments

In my situation, I want to subscribe an async method to an event when it is invoked, and I only need the method to execute once. Therefore, I use the SubscribeAwait operator. I also want to log the exceptions in the method execution so I search inside readme and find OnErrorResumeAsFailure() function might be the one I want.

From the Interoperability with async/await section of readme, I saw these sentences:

Methods that convert to such Task (for example FirstAsync, LastAsync) transform OnErrorResume's Exception into a Faulted Task, similar to OnCompleted(Exception). Note that since the Catch operator does not capture OnErrorResume, if you want integrated error handling, please use OnErrorResumeAsFailure() to convert OnErrorResume(Exception) to OnCompleted(Exception).

And I thought only the methods that return a Task can use OnErrorResumeAsFailure()

However, at the bottom of the readme I saw this:

Similar to IObservable<T>, if you want to stop the stream when an OnErrorResume occurs, you connect OnErrorResumeAsFailure in the method chain.

So I think OnErrorResumeAsFailure() should work on SubscribeAwait. But when I actually use this method in my code it does not work as expected, and since I'm not familiar with Rx, I think it might be my own issue and not a bug, but don't know how to achieve the function I want.

Example Code (there might be incorrect usage of operators):

Observable.FromEventHandler(
        handler => EventClass.AEvent += handler,
        handler => EventClass.AEvent -= handler)
    .Take(1)
    .OnErrorResumeAsFailure()
    .SubscribeAwait((_, ct) => TestAsync(ct),
        ex => Console.WriteLine(ex.Message),
        result => Console.WriteLine(result.IsFailure));

async ValueTask TestAsync(CancellationToken ct)
{
    await Task.Delay(1);
    throw new Exception("Exception Thrown by TestAsync");
}

Expected Output:

True

Actual Output:

Exception Thrown by TestAsync
False

lxymahatma avatar Mar 13 '25 09:03 lxymahatma