Reputation: 1613
When we do await for something inside an eventhandler in the activity lifecycle, goes to the next event handler when doing the "async" part.
We are doing things inside OnCreate (or OnStart), some of them take time. So we use async in order to make the app responsive during this time. But when we do this it jumps to the OnResume part.
While it does complete all the jobs it was required to do, It's not the way we need it to happen. We can't make the OnResume happen before OnCreate finishes
Should we do this in a different way?
Upvotes: 2
Views: 696
Reputation: 952
Welcome to the world of async-xamarin. The base Activity
class code does not await the life-cycle methods and so yes, the OnStart()
and OnResume()
methods will be called while an awaited call in OnCreate()
is running. The easiest way is to keep all code within a single life-cycle method
public class MyActivity : Activity
{
private Data data;
public async void OnCreate()
{
data = await getDataFromServerAsync();
calculateValues(data);
showValues(data);
}
}
If you need to split the code across methods, you need to get creative. For example, if you need to load data from a server only when the activity launches, but every time a activity resumes it needs to update the display using local data as well, you could check that all required preprocesses have been done:
public class MyActivity : Activity
{
private Data data;
public async void OnCreate()
{
data = await getDataFromServerAsync();
await calculateValuesIncludingLocalData(data);
showValues(data);
}
public void OnResume()
{
if(data != null)
{
await calculateValuesIncludingLocalData(data);
showValues(data);
}
}
}
Note there will be issues when stepping through this code as the async
method in OnCreate()
could easily complete before you get to step through the OnResume()
method.
Upvotes: 1