I'm working on a xamarin android app using Mvvm Light and I've got a method I'm calling and I'd like to change it to an async method but I'm not sure how. Just curious as to how to do this. It's for an Xamarin Android app in Visual Studio's
Call to method :
protected override void onResume()
{
ObservableCollection locObs = Vm.ShowLocations();
}
Method :
public ObservableCollection<Location> ShowLocations()
{
if (Debugger.IsAttached)
{
if (Locations != null)
{
var locationsCopy = Locations.ToList();
Locations = new ObservableCollection<Location>(locationsCopy);
}
Election elec = IntentManager.Instance.CurrentElection;
elec.Locations = new System.Collections.ObjectModel.ObservableCollection<Location>();
Location loc = new Location();
loc.Name = "Alan Middle School";
loc.Address = "300 S. County Farm Road";
elec.Locations.Add(loc);
Location loc2 = new Location();
loc2.Name = "Bill High School";
loc2.Address = "100 S. County Farm Road";
elec.Locations.Add(loc2);
Location loc3 = new Location();
loc3.Name = "Cameron Fire Station";
elec.Locations.Add(loc3);
Location loc4 = new Location();
loc4.Name = "Danvill Senior Center";
elec.Locations.Add(loc4);
Locations = elec.Locations;
}
return Locations;
}
this will be replaced with a service call. It's temporary I'm just asking for tips on Async or examples.
Once you have a service call, you can call it asynchronously with await
as such:
var locations = await GetLocationsAsync();
elec.Locations = new ObservableCollection<Location>(locations);
This requires the calling method to be async
, as such:
public async Task<ObservableCollection<Location>> ShowLocationsAsync()
{
var locations = await GetLocationsAsync();
elec.Locations = new ObservableCollection<Location>(locations);
return elec.Locations;
}
Which can then be called as:
protected override async void onResume()
{
ObservableCollection locObs = await Vm.ShowLocationsAsync();
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments