Can I do a synchronous request with volley?

后端 未结 8 1590
执念已碎
执念已碎 2020-11-22 11:02

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 ar

8条回答
  •  情歌与酒
    2020-11-22 12:00

    It is probably recommended to use the Futures, but if for whatever reason you don't want to, instead of cooking your own synchronized blocking thing you should use a java.util.concurrent.CountDownLatch. So that would work like this..

    //I'm running this in an instrumentation test, in real life you'd ofc obtain the context differently...
    final Context context = InstrumentationRegistry.getTargetContext();
    final RequestQueue queue = Volley.newRequestQueue(context);
    final CountDownLatch countDownLatch = new CountDownLatch(1);
    final Object[] responseHolder = new Object[1];
    
    final StringRequest stringRequest = new StringRequest(Request.Method.GET, "http://google.com", new Response.Listener() {
        @Override
        public void onResponse(String response) {
            responseHolder[0] = response;
            countDownLatch.countDown();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            responseHolder[0] = error;
            countDownLatch.countDown();
        }
    });
    queue.add(stringRequest);
    try {
        countDownLatch.await();
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
    if (responseHolder[0] instanceof VolleyError) {
        final VolleyError volleyError = (VolleyError) responseHolder[0];
        //TODO: Handle error...
    } else {
        final String response = (String) responseHolder[0];
        //TODO: Handle response...
    }
    

    Since people seemed to actually try to do this and ran into some trouble I decided I'd actually provide a "real life" working sample of this in use. Here it is https://github.com/timolehto/SynchronousVolleySample

    Now even though the solution works, it has some limitations. Most importantly, you can't call it on the main UI thread. Volley does execute the requests on the background, but by default Volley uses the main Looper of the application to dispatch the responses. This causes a deadlock as the main UI thread is waiting for the response, but the Looper is waiting for onCreate to finish before processing the delivery. If you really really want to do this you could, instead of the static helper methods, instantiate your own RequestQueue passing it your own ExecutorDelivery tied to a Handler using a Looper which is tied to different thread from the main UI thread.

提交回复
热议问题