I am trying to use PortableRest to make an Async call to a Web API 2.2 Rest service from Xamarin Forms.
I think I have some kind of deadlock / synchronisationcontext issue but I cannot work it out (newbie to async etc).
Can anyone please help?
My controller test method (removed any call to database) -
public IEnumerable<ContentModel> GetTestRest()
{
return new List<ContentModel> {
new ContentModel() {Categoryid = 1, Title = "Title"}};
}
My Unit Test Passes -
[TestMethod]
public async Task TestRest()
{
MyNewsApiClient MyNewsApiClient = new MyNewsApiClient();
var models = await MyNewsApiClient.TestRest();
int count = models.Count;
Assert.AreEqual(1, count);
}
My PortableRest Proxy (PCL) Method -
public async Task<List<ContentModel>> TestRest()
{
var request = new RestRequest();
request.Resource = "Content/GetTestRest";
return await ExecuteAsync<List<ContentModel>>(request);
}
Xamarin Forms ContentPage (PCL) -
public partial class NewsType1CP : ContentPage
{
public NewsType1CP ()
{
InitializeComponent ();
}
protected override void OnAppearing ()
{
LoadData (); // this is a sync call of an async method, not sure how else to approach, make OnAppearing async?
}
public async Task LoadData ()
{
Debug.WriteLine ("LoadData");
HeaderLabel.Text = "Load Data!";
MyNewsApiClient api = new MyNewsApiClient ();
var cm = await api.TestRest ();
// this will work on its own, control returns to this method - await api.GetDelay ();
HeaderLabel.Text = "After! - ";
NewsListView.ItemsSource = cm;
}
}
The await to api.TestRest() never results in HeaderLabel.After or ListView being set.
If I just add a test Proxy Method GetDelay() which does not call PortableRest via return await ExecuteAsync>(request);
public async Task<bool> GetDelay ()
{
await Task.Delay (1000);
return true;
}
Then all "works".
Thanks for your help, I will download the source code for PortableRest if required (using Nuget dll at present), just was not sure if missing something basic at this top level.