本文介紹了如何等待異步方法的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我需要返回值uId
。我在onResponse()
函數內的第一個LOG語句中獲得了正確的值。但當涉及到RETURN語句時,它返回空。
我認為onResponse()正在另一個線程上運行。如果是這樣,如何使getNumber()函數等待onResponse()函數執行完畢。(如thread.Join())
或者是否有其他解決方案?
編碼:
String uId;
public String getNumber() {
ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
Call<TopLead> call = apiInterface.getTopLead();
call.enqueue(new Callback<TopLead>() {
@Override
public void onResponse(Call<TopLead> call, Response<TopLead> response) {
String phoneNumber;
TopLead topLead = response.body();
if (topLead != null) {
phoneNumber = topLead.getPhoneNumber().toString();
uId = topLead.getUId().toString();
//dispaly the correct value of uId
Log.i("PHONE NUMBER, UID", phoneNumber +", " + uId);
onCallCallback.showToast("Calling " + phoneNumber);
} else {
onCallCallback.showToast("Could not load phone number");
}
}
@Override
public void onFailure(Call<TopLead> call, Throwable t) {
t.printStackTrace();
}
});
//output: Return uid null
Log.i("Return"," uid" + uId);
return uId;
推薦答案
您的方法執行異步請求。因此,操作”Return Uid;”不會等到您的請求完成,因為它們位于不同的線程上。
我可以推薦幾種解決方案
使用接口回調
public void getNumber(MyCallback callback) {
...
phoneNumber = topLead.getPhoneNumber().toString();
callback.onDataGot(phoneNumber);
}
您的回調接口
public interface MyCallback {
void onDataGot(String number);
}
最后,調用該方法
getNumber(new MyCallback() {
@Override
public void onDataGot(String number) {
// response
}
});
使用kotlin(我認為是時候使用kotlin而不是Java:)
fun getNumber(onSuccess: (phone: String) -> Unit) {
phoneNumber = topLead.getPhoneNumber().toString()
onSuccess(phoneNumber)
}
調用該方法
getNumber {
println("telephone $it")
}
這篇關于如何等待異步方法的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,