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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With