How to make a direct call to ReactiveCommand.Execute () in ReactiveUI 7 correctly?

I am trying to convert my project from ReactiveUI 6.5 to version 7. In the old version, I called

// var command = ReactiveCommand.Create...; // ... if(command.CanExecute(null)) command.Execute(null); 

to execute a command from my code.

The CanExecute method is now no longer available and is replaced by the IObservable<bool> property. Is CanExecute Observable automatically called if I just call Execute().Subscribe() or should I explicitly call it?

Now I have replaced the above code with

 command.Execute().Subscribe(); 
+5
source share
1 answer

I found three different solutions for invoking my CanExecute and Execute methods, as I could before in ReactiveUI 6.5:

Option 1

This is the same as calling in version 6.5, but we need to explicitly convert the command to ICommand:

 if (((ICommand) command).CanExecute(null)) command.Execute().Subscribe(); 

Option 2

 if(command.CanExecute.FirstAsync().Wait()) command.Execute().Subscribe() 

or asynchronous option:

 if(await command.CanExecute.FirstAsync()) await command.Execute() 

Option 3

Another option is to make us a way to extend InvokeCommand .

 Observable.Start(() => {}).InvokeCommand(ViewModel, vm => vm.MyCommand); 

This corresponds to the execution of the command, as indicated in the documentation .


To make it more convenient, I wrote a small extension method to provide the ExecuteIfPossible and GetCanExecute :

 public static class ReactiveUiExtensions { public static IObservable<bool> ExecuteIfPossible<TParam, TResult>(this ReactiveCommand<TParam, TResult> cmd) => cmd.CanExecute.FirstAsync().Where(can => can).Do(async _ => await cmd.Execute()); public static bool GetCanExecute<TParam, TResult>(this ReactiveCommand<TParam, TResult> cmd) => cmd.CanExecute.FirstAsync().Wait(); } 

You can use this extension method as follows:

 command.ExecuteIfPossible().Subscribe(); 

Note: you need to call Subscribe() at the end, as you need to call Execute() , otherwise nothing will happen.

Or if you want to use async and wait:

 await command.ExecuteIfPossible(); 

If you want to check if the command can be executed, just call

 command.GetCanExecute() 
+10
source

Source: https://habr.com/ru/post/1260506/


All Articles