Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call this async method in my Xamarin Forms when my app starts?

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.

like image 228
Pure.Krome Avatar asked Jul 30 '15 13:07

Pure.Krome


1 Answers

As far as the docs say, you have the Application.OnStart event which you can override:

Application developers override this method to perform actions when the application starts.

You can execute your async method there where it can actually be awaited:

public override async void OnStart()
{
    await LoadStorageDataAsync();
}
like image 103
Yuval Itzchakov Avatar answered Sep 22 '22 14:09

Yuval Itzchakov