lavilaso
lavilaso

Reputation: 27

how can an async method be executed synchronously in Xamarin.Forms

I am building a screen for my app in xamarin.forms the caul is based on a tabbedpage which is built dynamically based on a list of objects which I get as a result of consuming a service. After I call the method to consume the API that brings the list, I need to go through it based on certain data of it to fill an observable collection of viewmodels, which will be the tabs. The problem I have is that I do not know how to call the async method that consumes the API in a synchronized way so that the consumption of the API does not conflict with the operation of going through the list. Then a fraction of the code of my ViewModel:

public MonitoringViewModel()
    {
        LoadThings();
        Tabs = new ObservableCollection<MonitoringTabsViewModel>();
        foreach (PcThing t in Things)
        {
            Tabs.Add(new MonitoringTabsViewModel(t.description));
        }
    }


    private async void LoadThings()
    {
        Things = new List<PcThing>(await App.WebApiManager.GetCustomerThinksAsync());
    }

What I get is that in xamarin live player the app after a few seconds go from the green signal to the red one without showing anything, and in the log of it I get this: Target of GetEnumerator is null (NullReferenceException)

Upvotes: 1

Views: 2488

Answers (2)

fradsham
fradsham

Reputation: 141

Since you are doing this in the constructor , I would try the following:

using System.Threading.Tasks;

The risk here is if you are not in control of the LoadThings completing, it can hang.

public MonitoringViewModel()
{
    var task = Task.Run(async () => { await LoadThings();}
    Task.WaitAll(task); //block and wait for task to complete

Upvotes: 3

Bruno Caceiro
Bruno Caceiro

Reputation: 7189

public async Task<List<PcThing>> LoadThings()
{
    return await App.WebApiManager.GetCustomerThinksAsync();
}

And in your ViewModel

Things = LoadThings().GetAwaiter().GetResult();

Upvotes: 1

Related Questions