为了账号安全,请及时绑定邮箱和手机立即绑定

如何等待异步方法

如何等待异步方法

万千封印 2021-05-31 09:17:37
我需要返回值uId。我在onResponse()函数内的第一个日志语句中获得了正确的值。但是当涉及到 return 语句时,它返回null。我认为 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; 
查看完整描述

3 回答

  • 3 回答
  • 0 关注
  • 135 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号