priehl
priehl

Reputation: 664

Subscribing To ThrownExceptions in ReactiveUi

I am migrating to version 6 of Reactive UI, and am trying to more completely use the tools it provides, namely ThrownExceptions. Nothing happens when I subscribe to the thrown exceptions property. I'm sure I'm missing something just not sure what it is right now.

In my simplified example, there is a button with a command bound it it.

    public ReactiveCommand<object> Delete { get; private set; }

    public MainWindowViewModel()
    {
        Delete = ReactiveCommand.Create();
        Delete.Subscribe(e => CommandExec());
        Delete.ThrownExceptions.Subscribe(ex => HandleException(ex));

    }

    private object HandleException(Exception ex)
    {
        MessageBox.Show("Exception Handled");
        return null;
    }

    public IObservable<object> CommandExec()
    {
        throw new Exception("throwing");
    }

My assumption is that I would see an "Exception Handled" MessageBox when the exception was thrown. I'm sure i'm subscribing to something, it's just not clear what it is right now.

Upvotes: 2

Views: 2177

Answers (1)

Ana Betts
Ana Betts

Reputation: 74654

ThrownExceptions only applies to the background operation declared with CreateAsyncXYZ:

var someCmd = ReactiveCommand.CreateAsyncObservable(_ => 
    Observable.Throw<Unit>(new Exception("Oh Noes!"));

someCmd.ThrownExceptions.Subscribe(ex => Console.WriteLine(ex.Message));

await someCmd.ExecuteAsync();
>>> Oh Noes!

In ReactiveUI, you should never put Interesting™ code inside the Subscribe block - Subscribe is solely to log the result of operations, or to wire up properties to other properties.

Upvotes: 5

Related Questions