ReactiveCommand的前后行动

Val*_*nik 2 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";
});
Run Code Online (Sandbox Code Playgroud)

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

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";
    }
});
Run Code Online (Sandbox Code Playgroud)

或这个:

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";
    }
});
Run Code Online (Sandbox Code Playgroud)

Ana*_*tts 6

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

Cmd = ReactiveCommand.CreateAsyncTask(_ => DoAsyncJob());
Cmd.IsExecuting.ToProperty(this, x => x.IsBusy, out isBusy);
Run Code Online (Sandbox Code Playgroud)

此外,永远不要写这个:

someObservable.Subscribe(async _ => 
Run Code Online (Sandbox Code Playgroud)

Subscribe知道异步的,的其返回值onNextvoid.相反,写下这个:

someObservable.SelectMany(async _ => {...}).Subscribe(x => {...});
Run Code Online (Sandbox Code Playgroud)

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