I'm learning how to use Google Volley these days. It's very convenient for fast networking. It seems that all the requests are running in background in Volley. For example:
volleyRequestQueue.add(new JsonObjectRequest(Method.POST, SIGNUP_URL, reqBody, new SignUpResponseListener(), new MyErrorListener()));
Using the above code, we can make a POST call which runs in background(non-blocking way). Now my question is : Is it possible to make the POST call in the blocking way? Why I need a blocking way to make a REST call? Because some calls, like sign in, should be done before doing something else.
Thanks
Volley supports blocking request via RequestFutures. You create a normal request but set its callbacks as your request future, which is just volley's extension of a standard java futures. The call to future.get() will block.
It looks something like this
RequestFuture<JSONObject> future = RequestFuture.newFuture();
JsonObjectRequest request = new JsonObjectRequest(Method.POST, SIGNUP_URL, reqBody, future, future)
volleyRequestQueue.add(request);
try {
JSONObject response = future.get();
} catch (InterruptedException e) {
} catch (ExecutionException e) {
}
Here's a clearer answer which handles InterruptedException
properly as well as timeout. Note that the only time you would want to swallow the interrupt and continue is if you specifically intend to use the interrupt to cancel responding to the request.
RequestFuture<JSONObject> future = RequestFuture.newFuture();
JsonObjectRequest request = new JsonObjectRequest(Method.POST, SIGNUP_URL, reqBody, future, future);
volleyRequestQueue.add(request);
try {
JSONObject response = null;
while (response == null) {
try {
response = future.get(30, TimeUnit.SECONDS); // Block thread, waiting for response, timeout after 30 seconds
} catch (InterruptedException e) {
// Received interrupt signal, but still don't have response
// Restore thread's interrupted status to use higher up on the call stack
Thread.currentThread().interrupt();
// Continue waiting for response (unless you specifically intend to use the interrupt to cancel your request)
}
}
// Do something with response, i.e.
new SignUpResponseListener().onResponse(response);
} catch (ExecutionException e) {
// Do something with error, i.e.
new MyErrorListener().onErrorResponse(new VolleyError(e));
} catch (TimeoutException e) {
// Do something with timeout, i.e.
new MyErrorListener().onErrorResponse(new VolleyError(e));
}
If you want to do something exactly after the Volley request, use a callback listener onSuccess (SignUpResponseListener in that case) and put the code there. This is the best practice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With