Search code examples
mvvmmvvmcross

UI Thread issue with view model in MVVMCross


I am using MVVMCross with my cross-platform Windows Phone and Android app. In the core project's main view model, I am doing some background work using TPL and I want to make sure that in the callback, when I make changes to the properties of the view model which will trigger UI change, that the code is run on UI thread, how do I achieve this?

For code, here is how it likes

    private MvxGeoLocation _currentLocation;
    private Task<MvxGeoLocation> GetCurrentLocation()
    {
        return Task.Factory.StartNew(() =>
            {
                while (_currentLocation == null && !LocationRetrievalFailed)
                {
                }
                return _currentLocation;
            });
    }

    var location = await GetCurrentLocation();
    if (LocationRetrievalFailed)
    {
        if (location == null)
        {
            ReverseGeocodingRequestFailed = true;
            return;
        }
        // Show toast saying that we are using the last known location
    }
    Address = await GooglePlaceApiClient.ReverseGeocoding(location);

Solution

  • Method RequestMainThreadAction is now obsolete. Today you have to do

    var dispatcher = Mvx.Resolve<IMvxMainThreadAsyncDispatcher>();
    await dispatcher.ExecuteOnMainThreadAsync(()=> { .... });