Beware an exception in a ReactiveCommand

The Reactive UI class ReactiveCommand can be used to implement a view model’s commands as per the following:

Synchronize = ReactiveCommand.Create(_ => true, DoSynchronize);

This is excellent and works like RelayCommand and DelegateCommand from other MVVM frameworks, in that the first argument of the Create method handles the CanExecute and the second is the Action to be executed when ICommand.Execute is called.

One problem this usage has, is in the case of an exception within the command’s action. As Reactive UI uses Reactive Extensions it also handles errors in the same way.

When an error occurs in Reactive Extensions the default behaviour after an OnError is that subscribers are unsubscibed, in other words no further calls are made to your subscribed Action.

In the case of ReactiveUI’s ReactiveCommand this means if an exception occurs during the Action the command essentially disconnects itself and further commands are ignored. So a simpler way of solving this is to use ReactiveAsyncCommand.

Synchronize new ReactiveAsyncCommand(null);
Synchronize.RegisterAsyncAction(_ => DoSynchronize());

This way a new IObservable is created each time a command is executed, thus an exception will simply stop the current IObservable and the next time the command is called a new one is created.