2
votes

I want to set busy flag and status bar text before command execution, and after it completes — reset flag and text. My working code is here:

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";
});

Is it possible to do this in the "right way"? Like this:

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";
    }
});

Or this:

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

1 Answers

6
votes

Actually, this is already built into ReactiveCommand:

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

Also, never ever write this:

someObservable.Subscribe(async _ => 

Subscribe is not aware of async, its return value of the onNext is void. Instead, write this:

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

You can put whatever you want in the Subscribe block, I usually write some sort of logging statement.