0
votes

I'm trying to create a ReactiveCommand within the constructor of a ViewModel:

IObservable<bool> canExecute = this
  .WhenAnyValue(x => x.InsertableItems, x => x.IsRefreshing,
  (insertableItems, isRefreshing) => !isRefreshing && insertableItems > 0);

canExecute.Subscribe(x => this.Logger.LogInformation("Can execute changed: {0}", x));

this.ConvertCmd = ReactiveCommand.CreateAsyncTask(canExecute, ConvertCmdExecute);

ConvertCmd is then bound to the Command property of a button in my GUI,

<Button Content="Convert" Command="{Binding ConvertCmd, Mode=OneWay}" />

However, the GUI button remains greyed out and never becomes enabled

A few things to note:

  • In my logger, I'm seeing several updates "Can execute changed: ...", with the very latest / last value being True (as expected). So seems like my IObservable canExecute does create the correct, expected sequence of values; a sequence which eventually ends with true.
  • When I create the command using ReactiveCommand.CreateAsyncTask(ConvertCmdExecute) - i.e. omitting the canExecute parameter - the button is enabled and executes ConvertCmdExecute on click, also just as expected. So seems like databinding itself etc. works.

I'm a loss here. Does anyone have an idea of why the button never becomes enabled in my original scenario?

1

1 Answers

1
votes

As usual, after spending hours on the issue, I find my own answer just moments after posting this...

Seems like this was a threading issue. The Subscriptions got executed on unknown, potentially varying threads. The following fixes the code - even though to be honest, I'm not entirely sure why it is necessary to have this run on the Dispatcher.

IObservable<bool> canExecute = this
  .WhenAnyValue(x => x.InsertableItems, x => x.IsRefreshing,
  (insertableItems, isRefreshing) => !isRefreshing && insertableItems > 0)
  .ObserveOnDispatcher();  // this fixes the issue