HesenliEldar
HesenliEldar

Reputation: 115

Volley response in Other thread

I understood that volley send request in other thread but handle response in Main UI Thread . I would like to know how can I handle Volley's response in other thread or do I have to use Async Task with it? Thanks in advance.

Upvotes: 5

Views: 972

Answers (1)

Dhruv Jagetiya
Dhruv Jagetiya

Reputation: 1043

You can do this by making a blocking request with the help of volley's RequestFuture. Like this:

Runnable blockingRequest = new Runnable() {

    @Override
    public void run() {
        RequestFuture<JSONObject> future = RequestFuture.newFuture();
        JsonObjectRequest request = new JsonObjectRequest(URL, new JSONObject(), future, future);
        requestQueue.add(request);

        try {
          JSONObject response = future.get(); // this will block
        } catch (InterruptedException e) {
          // exception handling
        } catch (ExecutionException e) {
          // exception handling
        }
    }
};
Thread n = new Thread(blockingRequest);
n.start();

As you can see the response, which is blocking, will stay on the same thread, as opposed to UI thread. If you want to transfer the response to some other thread, you will need to use Thread-safe shared variables and synchronize accordingly.

Upvotes: 1

Related Questions