java - 如何等待异步方法

标签 java android retrofit2

我需要返回值 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; 

最佳答案

您的方法执行异步请求。因此“return uId;”操作不会等到您的请求完成,因为它们在不同的线程上。

我可以建议几种解决方案

  1. 使用接口(interface)回调

     public void getNumber(MyCallback callback) {
       ...
        phoneNumber = topLead.getPhoneNumber().toString();
        callback.onDataGot(phoneNumber);
     }
    

你的回调接口(interface)

     public interface MyCallback {

        void onDataGot(String number);
     }

最后,调用方法

getNumber(new MyCallback() {
    @Override
    public void onDataGot(String number) {
    // response
    }
});
  1. 使用 Kotlin 时(我认为是时候使用 Kotlin 而不是 Java 了:))

    fun getNumber(onSuccess: (phone: String) -> Unit) {
      phoneNumber = topLead.getPhoneNumber().toString()
      onSuccess(phoneNumber)
    }
    

调用方法

    getNumber {
      println("telephone $it")
    }

关于java - 如何等待异步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51402623/

相关文章:

android - firebase jobdispatcher-我无法添加依赖项

kotlin - Kotlin中的RxJava2使用Retrofit-Vertx IllegalStateException消息== null

java - Postgresql JDBC 驱动程序是否支持 Pgpass 身份验证?

java - 如何使用 OOP 概念将 arraylist 对象设置为表

java - 与数据库一起使用的 Android recyclerview 列表不起作用

android - 在华为设备上设置默认 Android 启动器?

java - RxJava2 轮换后调用 onNext Consumer 两次

java - Android + Retrofit 2 + GSON = 无法为接口(interface)调用无参数构造函数

java - 将数组中的双空格替换为单空格

java - TCP 客户端无法从服务器读取数据