如何在 ReactiveUI 7 中直接调用 ReactiveCommand.Execute() 正确?

How do I make a direct call to ReactiveCommand.Execute() in ReactiveUI 7 correct?

我正在尝试将我的项目从 ReactiveUI 6.5 转换为版本 7。在旧版本中我调用了

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

为了从我后面的代码中执行命令。

现在 CanExecute 方法不再可用,取而代之的是 IObservable<bool> 的 属性。如果我只是调用 Execute().Subscribe() 还是必须显式调用它,CanExecute Observable 会自动调用吗?

现在我用

替换了上面的代码
command.Execute().Subscribe();

我找到了三种不同的解决方案来调用我的命令的 CanExecuteExecute 方法,就像我以前在 ReactiveUI 6.5 中一样:

选项 1

这等同于6.5版本中的调用,但我们需要将命令显式转换为ICommand:

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

选项 2

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

或异步变体:

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

选项 3

另一种选择是让我们使用 InvokeCommand 扩展方法。

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

这尊重命令的可执行性,如 documentation 中所述。


为了让它更舒服,我写了一个小的扩展方法来提供一个 ExecuteIfPossible 和一个 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();
}

您可以按如下方式使用此扩展方法:

command.ExecuteIfPossible().Subscribe();

注意:最后需要调用Subscribe(),就像调用Execute()一样,否则什么也不会发生。

或者如果你想使用异步和等待:

await command.ExecuteIfPossible();

如果要检查命令是否可以执行,只需调用

command.GetCanExecute()