LocoMike LocoMike - 5 months ago 561
Java Question

Can I do a synchronous request with volley?

Imagine I'm in a Service that already has a background thread. Can I do a request using volley in that same thread, so that callbacks happen synchronously?

There are 2 reasons for this:
- First, I do not need another thread and it would be a waste to create it.
- Second, if I'm in a ServiceIntent, the execution of the thread will finish before the callback, and therefor I will have no response from Volley. I know I can create my own Service that has some thread with a runloop I can control, but it would be desirable having this functionality in volley.

Thank you!

Answer

It looks like it is possible with Volley's RequestFuture class. For example, to create a synchronous JSON HTTP GET request, you can do the following:

RequestFuture<JSONObject> future = RequestFuture.newFuture();
JsonObjectRequest request = new JsonObjectRequest(URL, null, future, future);
requestQueue.add(request);

try {
  JSONObject response = future.get(10, TimeUnit.SECONDS); // Blocks for at most 10 seconds.
} catch (InterruptedException e) {
  // Exception handling
} catch (ExecutionException e) {
  // Exception handling
}
Comments