HttpClient and where to call web services on application load?

KyleRobitailleKyleRobitaille USUniversity ✭✭
edited August 2015 in Xamarin.Android

Hi,

I'm trying to figure out the best place to make my web service calls when my application loads. My API calls themselves use HttpClient and are async functions that store the data they retrieve and return a string for a status code.

I basically have 2 functions (2 api calls) which need to be called and data retrieved, each time my app starts up. I was originally doing a check in OnResume() to see if data had already been fetched, and if not to make the API call. Those calls looked like this:

    `async public Task ApiCall1(){
        progressBar.Visibility = ViewStates.Visible;
        string status = await APIUtilities.API1(someParam);
        if(status == "positive"){
            //Update UI
        }else{
            //Display alert with status message
        }   

        progressBar.Visibility = ViewStates.Gone;
    }`





    `async public override void OnResume ()
    {
        base.OnResume ();

        await ApiCall1();

    }`

This seemed to be working Ok but I was never really sure if it was the correct way to go about things. After speaking with someone I work with, he suggested there is no reason the API calls shouldn't be able to exist in OnCreate() so they get called immediately when the application is created. So i've now changed it so the call is being made in OnCreate and it looks like the below:

    `public override void OnCreate (Bundle savedInstanceState)
    {
        base.OnCreate (savedInstanceState);
        //Some set up code
        ApiCall1();
    }`

The ApiCall1() function is basically the same, the only difference is because it is being called in OnCreate(), I can't guarentee that my items have been loaded (like the progressBar) so I have to handle the visible/invisible properties of that differently. I do get warnings now because in OnCreate() I haven't been using the await keyword, as I don't want to halt the process in OnCreate(), I still want my UI to load.

Do I have a misunderstanding about how await works? Or am I approaching that correctly? If any of this wasn't clear let me know and I can try to explain or give more code examples, but I'm really looking for how you guys recommend handling api calls on application load and where to put awaits.

Thank you

Answers

Sign In or Register to comment.