我正在使用 restsharp 从我正在做的 API 中获取数据,我想创建一个名为“ApiInterface”的类,它将在 Xamarin(Android、iOS、Windows...)中用于调用API。
这个类有它的 RestClient 和可以从代码的任何部分调用的函数,因为它是一个单例。
例如,我将有一个像这样的 MainActivity.cs。 (调用我的 getData 函数并处理我收到的数据)。
Button buttonListaIntereses = FindViewById<Button> (Resource.Id.myButton);
buttonListaIntereses.Click += delegate {
ApiInterface.Instance.getData(response2=>
{
Intent displayMessage = new Intent(this, typeof(DisplayMessage));
//Put info in Extra for the new screen.
displayMessage.PutExtra("content", response2.Content);
StartActivity(displayMessage);
});
};
但是在 APIInterface 中,我想获取像 cookie 这样的公共(public)数据。
public async void getData(Action <IRestResponse> onDone)
{
RestRequest request = new RestRequest("getData", Method.GET);
//Execute ASYNC the rest request
m_Client.ExecuteAsync (request, response =>
{
//Do my stuff with headers.
string lCookie = response.Headers.ToList().Find(x => x.Name == "Cookie").Value.ToString();
//Execute the OnDone
onDone();
});
}
我的问题是我不确定如何在 getData 中执行我的 OnDone 和/或如何调用 getData 函数。
谢谢!
请您参考如下方法:
我会放弃使用回调并利用 C# 的 Async/Await 特性
buttonListaIntereses.Click += async delegate {
var response = await ApiInterface.Instance.getData();
LaunchResponseActivity(response);
};
public void LaunchResponseActivity(IRestResponse response)
{
Intent displayMessage = new Intent(this, typeof(DisplayMessage));
//Put info in Extra for the new screen.
displayMessage.PutExtra("content", response.Content);
StartActivity(displayMessage);
}
public async Task<IRestResponse> getData()
{
RestRequest request = new RestRequest("getData", Method.GET);
var cancellationTokenSource = new CancellationTokenSource();
var restResponse = await client.ExecuteTaskAsync(request, cancellationTokenSource.Token);
//Do my stuff with headers.
string lCookie = restResponse.Headers.ToList().Find(x => x.Name == "Cookie").Value.ToString();
return restResponse;
}
