I've been getting a bit of strange behavior from the mobile app I'm writing using Xamarin Forms, the premise is simple:
- Navigate to a new page (this happens asynchronously)
- Retrieve some data (asynchronously as well)
- Bind data to view
Because I'm using mvvm I can't hook into any of the page events (appearing/disappearing/etc.) so I can only start retrieving data from the constructor (bad idea, I know).
That's where (I think) the issue lies:
the navigator (running on the UI Thread) asynchronously resolves the view and viewmodel the viewmodel can't load the data asynchronously from the constructor so it blocks the UI Thread untill the loading is done.
And as long as your network connection is fast enough you might not even notice it, but when it does take too long the system appears to think it's in a deadlock and terminates.
So I've tried to solve this by using
Task.Factory.StartNew(() => { GetData(); });
in the constructor and this works about 80% of the time but, as I've discovered, starting a new task does not guarantee a new Thread.
So once in a while the data retrieval task will run on the UI Thread, blocking it and take just slightly too long to load resulting in a crash.
Is there a clean way of async data loading with mvvm?