Can I do a synchronous request with volley?

后端 未结 8 1678
执念已碎
执念已碎 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

    Note @Matthews answer is correct BUT if you are on another thread and you do a volley call when you have no internet, your error callback will be called on the main thread, but the thread you are on will be blocked FOREVER. (Therefore if that thread is an IntentService, you will never be able to send another message to it and your service will be basically dead).

    Use the version of get() that has a timeout future.get(30, TimeUnit.SECONDS) and catch the error to exit your thread.

    To match @Mathews answer:

            try {
                return future.get(30, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                // exception handling
            } catch (ExecutionException e) {
                // exception handling
            } catch (TimeoutException e) {
                // exception handling
            }
    

    Below I wrapped it in a method & use a different request:

       /**
         * Runs a blocking Volley request
         *
         * @param method        get/put/post etc
         * @param url           endpoint
         * @param errorListener handles errors
         * @return the input stream result or exception: NOTE returns null once the onErrorResponse listener has been called
         */
        public InputStream runInputStreamRequest(int method, String url, Response.ErrorListener errorListener) {
            RequestFuture future = RequestFuture.newFuture();
            InputStreamRequest request = new InputStreamRequest(method, url, future, errorListener);
            getQueue().add(request);
            try {
                return future.get(REQUEST_TIMEOUT, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                Log.e("Retrieve cards api call interrupted.", e);
                errorListener.onErrorResponse(new VolleyError(e));
            } catch (ExecutionException e) {
                Log.e("Retrieve cards api call failed.", e);
                errorListener.onErrorResponse(new VolleyError(e));
            } catch (TimeoutException e) {
                Log.e("Retrieve cards api call timed out.", e);
                errorListener.onErrorResponse(new VolleyError(e));
            }
            return null;
        }
    

提交回复
热议问题