本文介紹了如何等待異步方法的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問(wèn)題描述
我需要返回值uId
。我在onResponse()
函數(shù)內(nèi)的第一個(gè)LOG語(yǔ)句中獲得了正確的值。但當(dāng)涉及到RETURN語(yǔ)句時(shí),它返回空。
我認(rèn)為onResponse()正在另一個(gè)線程上運(yùn)行。如果是這樣,如何使getNumber()函數(shù)等待onResponse()函數(shù)執(zhí)行完畢。(如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;
推薦答案
您的方法執(zhí)行異步請(qǐng)求。因此,操作”Return Uid;”不會(huì)等到您的請(qǐng)求完成,因?yàn)樗鼈兾挥诓煌木€程上。
我可以推薦幾種解決方案
使用接口回調(diào)
public void getNumber(MyCallback callback) {
...
phoneNumber = topLead.getPhoneNumber().toString();
callback.onDataGot(phoneNumber);
}
您的回調(diào)接口
public interface MyCallback {
void onDataGot(String number);
}
最后,調(diào)用該方法
getNumber(new MyCallback() {
@Override
public void onDataGot(String number) {
// response
}
});
使用kotlin(我認(rèn)為是時(shí)候使用kotlin而不是Java:)
fun getNumber(onSuccess: (phone: String) -> Unit) {
phoneNumber = topLead.getPhoneNumber().toString()
onSuccess(phoneNumber)
}
調(diào)用該方法
getNumber {
println("telephone $it")
}
這篇關(guān)于如何等待異步方法的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,