I made a Connection class, where I have everything related to connection to REST API, including URL, generic methods and it's working as intended.
Then I have LocationPage, where locations are displayed. I'm creating those location elements in code behind (LocationPage.xaml.cs) and putting them into grid.
Now the problem comes, since it takes some time for data to get fetched from API, it breaks my app with exception: "Object referenced or not null" (something in those lines).
I'm setting BindingContext to LocationViewModel
LocationPage.xaml.cs
public partial class LocationPage : ContentPage
{
private LocationViewModel lvm;
public LocationPage ()
{
InitializeComponent ();
BindingContext = lvm = new LocationViewModel();
}
LocationViewModel.cs
public LocationViewModel()
{
LoadLocationsAsync();
}
public async Task LoadLocationsAsync()
{
// going to connection class which return list of locations
_locations = await Connection.GetAllAsync<Location>("location");
}
private IList<Location> _locations;
public IList<Location> Locations
{
get { return _locations; }
set {
_locations = value;
OnPropertyChanged();
}
}
My question is. What is the correct way of loading async data in MVVM from REST API, And how to tell LocationPage.xaml.cs to wait until data is fetched in LocationViewModel AND only then it should start constructing elements in LocationPage codebehind and showing them on page, maybe even showing a spinner.
Thank you all!