ReactiveCommand的前后行动

时间:2014-08-19 11:23:29

标签: c# system.reactive reactiveui

我想在命令执行之前设置忙标志和状态栏文本,并在完成之后 - 重置标志和文本。我的工作代码在这里:

Cmd = ReactiveCommand.Create();
Cmd.Subscribe(async _ => 
{
    IsBusy = true;
    StatusBarText = "Doing job...";
    try
    {
        var organization = await DoAsyncJob();
        //do smth w results
    }
    finally
    {
        IsBusy = false;
        StatusBarText = "Ready";
});

是否有可能以正确的方式做到这一点"? 像这样:

Cmd = ReactiveCommand.CreateAsyncTask(_ => DoAsyncJob());
//how to do pre-action?
//is exists more beautiful way to to post-action?
Cmd.Subscribe(res =>
{
    try
    {
        //do smth w results
    }
    finally
    {
        IsBusy = false;
        StatusBarText = "Ready";
    }
});

或者这个:

Cmd = ReactiveCommand.CreateAsyncTask(_ => DoAsyncJob());
//is exists more beautiful way to to post-action?
Cmd.Do(_ => 
{
    IsBusy = true;
    StatusBarText = "Doing job...";
})
.Subscribe(res =>
{
    try
    {
        //do smth w results
    }
    finally
    {
        IsBusy = false;
        StatusBarText = "Ready";
    }
});

1 个答案:

答案 0 :(得分:6)

实际上,这已经内置在ReactiveCommand中:

Cmd = ReactiveCommand.CreateAsyncTask(_ => DoAsyncJob());
Cmd.IsExecuting.ToProperty(this, x => x.IsBusy, out isBusy);

此外,永远不要写这个:

someObservable.Subscribe(async _ => 

Subscribe 意识到异步,onNext的返回值为void。相反,写下这个:

someObservable.SelectMany(async _ => {...}).Subscribe(x => {...});

你可以在Subscribe块中放入你想要的任何东西,我通常会写一些日志语句。