Search code examples
asynchronousandroid-activityxamarin.androidxamarin.formsakavache

Xamarin.Forms - Android Activity with async OnCreate method


I'm running into the questions if it's a problem to mark FormsAppCompatActivity.OnCreate(Bundle bundle) as async? I have to fetch user-specific data from an AWS DynamoDB, and I need to retrieve the user from the Akavache cache before in order to query with the userId. Of course, I could also save the userId to the local settings or serialize the whole user object to be able to retrieve it synchronously.

I also don't expect performance issues during startup because the cache uses SQLite definitely exists. The only problem is that either I await Akavache's GetObject<T>(string key) and therefore, mark everything down to OnCreate as async, or I subscribe to the returned Observable and the following methods will try to query the user data without a valid userId, because the Observable hasn't returned yet.


Solution

  • Since you're using XF for development, the code LoadApplication(new App()); in OnCreate of MainActivity will hook the lifecycle event to App's lifecycle event in PCL.

    You didn't post any code, I guess that you place your code for data fetch after LoadApplication(new App());, then as you said it didn't return yet, otherwise the behavior should be different.

    I suggest you to call your task in the OnStart() of App in PCL and together use DependencyService to call into your async task for fetching data from PCL.