Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async command execution in MVVM light

I am wondering why MVVM light is missing command with async execution? I believe there are many cases where this could be useful, so let me name one.

Let's say that our UI contains one container that contains multiple screens. User can close a particular screen or a container with multiple screens. Let's say that a user has issued a close command on the container. Container in return invokes close command on each screen, and it needs to wait for screen to be closed. This in practice can means validating data. saving, etc. For this reason we need to issue an async call to keep the UI from becoming unresponsive, and also we need to wait for task to complete, in order to continue.

So, if we have something like this in Command

public RelayCommand CloseCommand
{
    get { return _closeCommand ?? _closeCommand = new RelayCommand( async () =>
    {
        foreach (var screen in Screens)
        {
            if (!await screen.CloseCommand.ExecuteAsync(null))
            {
                // do something
            }
        }
    }) }

}

We could also expose additional method on screen, but in my opinion it should be task of RelayCommand, since it already exist there.

Or there is a different methodology to handle such scenario?

like image 539
Goran Avatar asked Dec 30 '14 03:12

Goran


1 Answers

Probably because there are many different ways of doing it; I describe a few approaches in my MSDN article on the subject.

Asynchronous lifetime commands are especially tricky. Something like a "close" command must be carefully considered. Is there some indication that a close is in progress? What happens if the user closes more than once ("close" in particular can often be initiated by an OS or another app even if a "close button" is disabled)?

like image 57
Stephen Cleary Avatar answered Sep 28 '22 05:09

Stephen Cleary