Alex Rivera | Logout

How can I use async in an mvvmcross view model?

Asked 2013-06-19T09:01:00.250
28

I have a long running process in an mvvmcross viewmodel and wish to make it async (http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx).

The async keyword is currently supported in the beta channel for Xamarin.

Below is an example of how I'm currently implementing async. The IsBusy flag ccould be bound to a UI element and display a loading message.

Is this the correct way?

public class MyModel: MvxViewModel
{
    private readonly IMyService _myService;
    private bool _isBusy;

    public bool IsBusy
    {
        get { return _isBusy; }
        set { _isBusy = value; RaisePropertyChanged(() => IsBusy); ; }
    }

    public ICommand MyCommand
    {
        get
        {
            return new MvxCommand(DoMyCommand);
        }
    }

    public MyModel(IMyService myService)
    {
        _myService = myService;
    }

    public async void DoMyCommand()
    {
        IsBusy = true;
        await Task.Factory.StartNew(() =>
            {
                _myService.LongRunningProcess();
            });
        IsBusy = false;
    }

}
Edit
Report

1 Answer

4

Looks OK except I would add a try catch finally around that await.

    public async void DoMyCommand()
    {
        IsBusy = true;
        try{
            await Task.Factory.StartNew(() =>
                                        {
                _myService.LongRunningProcess();
            });
        }catch{
            //Log Exception
        }finally{
            IsBusy = false;
        }
    }

Further more I have an example on my blog using an MvxCommand with async. Very similar to your example http://deapsquatter.blogspot.com/2013/03/updating-my-mobile-apps-for-async.html

answered 2013-06-19T10:33:09.130

Your Answer