Writing an asynchronous RelayCommand implementing ICommand
If you are familiar with MVVM, then you are already familiar with relay commands. We use relay commands to map a method with the ICommand raised from a control. Below is the typical code snippet you may have seen a lot of time.
The class below is pretty simple; it accepts a method and allows you to associate it with a command. Whenever the command is invoked, it is relayed to the method we have passed on as “execute” param. It acts like a disconnected event, if I may say.
Since Action deals with void functions, we cannot get the async methods working. So I resorted for Func instead of Action and rewrote my RelayCommand to below.
Comments
- Anonymous
July 28, 2017
In our product, we had to have a less naive implementation : - as it is asynchronous, if the user spams the button, you don't want to trigger multiple request... So you need to monitor when the async function is started and when it is done.- as now the async function can do something long in the background, the user need to be notified about this.We've upgrade the ICommand to IAsyncCommand :public interface IAsyncCommand : ICommand, INotifyPropertyChanged { bool BackgroundOperationRunning { get; set; }}in that case, we can use the BackgroundOperationRunning to theme the button to have some animation while the async callback is running. The RelayCommandAsync is more complicated but it allows us a nice user experience