Java socket.io wait for callback

529 Views Asked by At

My Activity code:

public String getValue(JSONObject data) {
    String value;
    socket.emit("request", data, new Ack() {
        @Override
        public void call(Object... args) {
            value = (String) args[1]; // how to wait for this value?
        });

    return value;
}

How do I wait for the value that came from the socket.io callback?

2

There are 2 best solutions below

0
On

For anyone who's still facing for the same issue, use CompletableFuture

public String request(JSONObject... objects) {
    CompletableFuture<String> future = new CompletableFuture<>();
    socket.emit("request", objects, (Ack) callback -> {
        future.complete(args[1].toString());
    });
    return future.join();
}

However, note that if answer wasn't provided, your code will be blocked until the answer would be provided by the server, however this is the question itself, so here you are

1
On

Try this

public class  getvalue extends AsyncTask<JSONObject,Void,String>{


          @Override
          protected String doInBackground(JSONObject... jsonObjects) {
              String value;
              socket.emit("request", jsonObjects, new Ack() {
                  @Override
                  public void call(Object... args) {
                      value = (String) args[1]; // how to wait for this value?
                  }
          });
          return value;
      }
          protected void onPostExecute(String result) {
              //result is the final String;
          }
      }

And after that go to Activity that you want to use this function in and try this :

 getvalue a=new getvalue();
            getvalue.execute(data);

Here is some useful link https://developer.android.com/reference/android/os/AsyncTask

AsyncTask Android example hopefully to work