I am writting a very basic Xamarin Forms Application, with Visual Studio for Mac. This application should work with PCL on Android and iOS.
I have an empty TableView on XAML file. What i want to do is to populate this TableView with data i will fetch from a webservice.
Here is my C# code:
HttpClient client = new HttpClient();
public async Task<List<MyItem>> LoadData()
{
try
{
var response = await client.GetAsync(new Uri("http://example.com/myservice.php"));
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<List<MyItem>>(content);
}
}
catch (Exception)
{
return null;
}
return null;
}
async void Handle_Clicked(object sender, System.EventArgs e)
{
activity_indicator.IsRunning = true;
var data = await LoadData();
activity_indicator.IsRunning = false;
mylistview.Root.Clear();
foreach (var item in data)
{
TableSection section = new TableSection() { Title = item.GroupTitle };
foreach (var subitem in item.subitems)
{
var cell = new TextCell() { Text = subitem.Title };
cell.Tapped += on_item_tapped;
section.Add(cell);
}
mylistview.Root.Add(section);
}
}
I am new to await and async programming. I used to develop native iOS application with iOS delegates. I have heard that a thread cannot update UI: Can i made some UI updates in LoadData() method for example ? So i am wondering if my code is good. It looks fine because it works, but i want to know if this is a good thing to work like this ?
async/await
here is the correct choice.await
on the UI thread will capture the current context and resume on that context when the asynchronous call completes which makes updating the ui after the call finishes trivial as you can see. One suggestions I'd make is to factor out the code inHandle_Clicked
into an item template but that has nothing to do withasync
. – JSteward