execute next statement only when awaited method complete its execution

trishelwoodtrishelwood ✭✭USMember ✭✭

I am calling API using HTTPClient PostAsync() method. This postasync method is in async task.
I am calling this task from my ViewModel using await keyword.
Like this

public ProfileViewModel() // Constructor { ABC(); } async void ABC() { IsBusy = true; await GetData(); Task.Delay(2000); App.IsAwaiting = true; } async Task<bool> GetData() { IsBusy = true; string response = await CallAPI.getFullProfile("1"); // CallAPI is a class where I created method to get profile of user using PostAsync method. App.IsAwaiting = true; App.Profile = JsonConvert.DeserializeObject<ProfileModel>(response); IsBusy = false; return true; }

Here when I call getFullProfile because of await keyword it goes to constructor's ending brackets. But I want to fill data after calling API.

So, when I try to debug for the first time, I don't get data but when I run my app second time, it shows data because in that time awaited method completes its execution.

Is there any way so that I compiler wait until data from API comes and then execute next statement ?

I tried to delay task by using Task.Delay() but it doesn't work.

Tagged:

Answers

  • kentuckerkentucker ✭✭✭✭✭ USMember ✭✭✭✭✭
    edited December 2016

    You should use await Task.Delay(2000) if you want it to pause. Never ever use async void outside of an event handler. You should change ABC to return a Task or Task of bool

    https://msdn.microsoft.com/en-us/magazine/jj991977.aspx?f=255&MSPPError=-2147217396

  • JimBennettJimBennett ✭✭✭✭ GBXamarin Team, Insider, University, Developer Group Leader ✭✭✭✭

    Why would you want your view model's constructor to wait for the data? Usually view models are created on the UI thread, and you won;dn't want that thread to block whilst it downloads data (which could take a looooong time on a slow connection, or if the call fails crash your app).

    It would be better to not load the data in the constructor, but instead have a different async method or command you call when your view is loaded, maybe showing a progress spinner whilst the data loads.

  • trishelwoodtrishelwood ✭✭ USMember ✭✭
    edited December 2016

    Thanks for commenting @kentucker and @JimBennett. Now I am calling this method in different task when my app starts. and it is working fine for me.

    I am wondering why this idea not came to my mind before posting this question. Sorry for taking your time.

    Thank you. :)

Sign In or Register to comment.