When my app is first starting, I need to load up some previously saved data. If it exists -> then goto the TabbedPage page. Otherwise, a Login page.
I'm not sure how I can call my async method in the app's ctor or even in another method?
How can I do this?
Here's my code..
namespace Foo
{
public class App : Application
{
public App()
{
Page page;
LoadStorageDataAsync(); // TODO: HALP!
if (Account != null)
{
// Lets show the dashboard.
page = new DashboardPage();
}
else
{
// We need to login to figure out who we are.
page = CreateAuthenticationPage();
}
MainPage = page;
}
... snip ...
}
So why is LoadStorageDataAsync
async? Because it's using the library PCLStorage and that is all async.
Can anyone help, please?
Using async methods in a constructors is considered as a bad code. You shouldn't use async methods in a class constructors.
You could try to change it to avoid deadlocks:
... but I won't recommend it.
As far as the docs say, you have the
Application.OnStart
event which you can override:You can execute your
async
method there where it can actually be awaited:Constructors can't be
async
, but event handlers can be. If you can you should move that logic to theOnStart
event handler (or a more appropriate one):If you can't, you don't have a better choice than simply blocking synchronously on that task to get the result. You should be aware though that this can lead to deadlocks.
Take a step back, and think about how the UI works. When your app is initially shown, the framework constructs your ViewModel and View, and then it shows something immediately (as soon as possible). That's an inappropriate place for network activity.
Instead, what you should do is start the asynchronous operation and then (synchronously) load and show a "loading" page. When the asynchronous operation completes, then you can transition to your other pages (or to an "error" page if, say, the user does not have network access).
I'm not sure if Xamarin Forms is capable of data-binding to a page object, but if it is, then my
NotifyTaskCompletion
type may be helpful.