2016-04-07 38 views
1

我正在使用restsharp從API中獲取數據,我想做一個名爲「ApiInterface」的類,它將用於Xamarin(Android,iOS ,Windows ...)調用API。RestSharp on Response不知道如何調用回調

該類具有RestClient和funcions,它們將從代碼的任何部分調用,因爲它是單例。

因此,例如我會有一個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); 
    }); 
}; 

但是在API界面中,我希望獲得像Cookie這樣的常見數據。

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功能。

謝謝!

回答

2

我會從使用回調移開,並利用的C#

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; 
} 
+0

嗨安德烈斯,我沒有嘗試過你的代碼,我是新的使用異步/等待c#功能他們的優點是什麼? – Chopi

+0

你最好改變xamarin及其導航流程的所有界面。 – Chopi

1

Action參數onDone採用類型的參數IRestReponse

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 action with the received response 
     onDone(response); 
    }); 
} 
+0

的異步/等待功能優點謝謝lenkan! 我被卡住了! :) – Chopi

相關問題