Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

correct way to load data async in xamarin forms

What is the correct way to load data async to be able to show UI as fast as possible to user. For example

I have a xamarin forms projekt, containing a map component. I want to show the map before I get the users current location(from gps) and some locations/pins that are fetched from a server. I have seen these two approaches

1) From constructor call an async method

   Map mMyMap;
   ctor()
   {
       InitializeCompeont();
       InitAsync();
   }
   private async void InitAsync()
   { 
      var pins = await GetPinsFromServer();
      mMyMap.Pins.Add(pins)
   }

2) in On appearing

 ctor()
  {
   InitalizeComponent()
  }
  protected override async void OnAppearing()
  { 
      var pins = await GetPinsFromServer();
       mMyMap.Pins.Add(pins)
   }

Both approaces seems to "work", but Im I fooling myself calling the async method from constructor?

Ive also managed to set BindingContext async both ways and it binds correctly

Is there any difference?

like image 447
Cowborg Avatar asked Sep 24 '18 09:09

Cowborg


People also ask

How do I use static resources in xamarin form?

The key is used to reference a resource from the ResourceDictionary with the StaticResource or DynamicResource markup extension. The StaticResource markup extension is similar to the DynamicResource markup extension in that both use a dictionary key to reference a value from a resource dictionary.


1 Answers

There is a difference in timing and when your load data will be called. If done in the page ctor it will be called once and only once when that page is first created.

If done in OnAppearing the call will happen prior to the page being shown and can be called more than once. For example, if you push another page on top of it and then popped it OnAppearing would get called again reloading your data, which might be okay to do if that other page modified the data being displayed on the previous page. Otherwise, you're potentially making unnecessary load data calls.

It is worth noting that OnAppearing and OnDisappearing aren't always consistently called at the same time on different platforms. For example, if you used the built-in sharing on Android or iOS one might fire both events, but the other might not fire any at all.

Also, I'd make sure you're making use of Task.Run(); to run any long running tasks on a background thread, to ensure you're not locking up the main thread, and potentially set a bool to show/hide a spinner if necessary to know when your background task starts and ends.

like image 51
Nick Peppers Avatar answered Sep 17 '22 11:09

Nick Peppers