Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for an asynchronous method

I need to return the value uId. I am getting the correct value in the first log statement inside the onResponse() function. But when it comes to the return statement it returns null.

I think that onResponse() is running on another thread. If so, how can I make the getNumber() function wait till the onResponse() function finishes execution.(Like thread.join())

Or is there any other solution?

code :

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; 
like image 284
Abhijith K Avatar asked Jul 18 '18 12:07

Abhijith K


People also ask

How do you wait for an async function to finish JavaScript?

The await operator is used to wait for a Promise. It can be used inside an Async block only. The keyword Await makes JavaScript wait until the promise returns a result. It has to be noted that it only makes the async function block wait and not the whole program execution.

What happens if an async method is not awaited?

The call to the async method starts an asynchronous task. However, because no Await operator is applied, the program continues without waiting for the task to complete. In most cases, that behavior isn't expected.

How do you run asynchronous method?

The simplest way to execute a method asynchronously is to start executing the method by calling the delegate's BeginInvoke method, do some work on the main thread, and then call the delegate's EndInvoke method. EndInvoke might block the calling thread because it does not return until the asynchronous call completes.

When an asynchronous method is executed the?

When a asynchronous method is executed, the code runs but nothing happens other than a compiler warning.


1 Answers

Your method performs an async request. So the action "return uId; " doesn't wait until your request finishes because they are on different threads.

There are several solutions I can suggest

  1. Use an interface callback

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

Your callback interface

     public interface MyCallback {

        void onDataGot(String number);
     }

And finally, calling the method

getNumber(new MyCallback() {
    @Override
    public void onDataGot(String number) {
    // response
    }
});
  1. When using Kotlin (I think it's time for you to use Kotlin instead of Java :))

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

Calling the method

    getNumber {
      println("telephone $it")
    }
like image 165
David Avatar answered Sep 29 '22 09:09

David