Volley——ExecutorDelivery

Posted Fishbonell

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Volley——ExecutorDelivery相关的知识,希望对你有一定的参考价值。

  在的StringRequest中,我们这样一个方法,还没有追踪过。

    @Override
    protected void deliverResponse(String response) {
        mListener.onResponse(response);
    }

 

  这个方法,会在我们请求结束后调用,但它是如何工作的,我们还没有阅读。通过对前面代码的阅读,我们会在ExecutorDelivery的run方法中,找到这个方法。  

 

  这整个过程要从RequestQueue的初始化说起:

    public RequestQueue(Cache cache, Network network, int threadPoolSize) {
        this(cache, network, threadPoolSize,
                new ExecutorDelivery(new Handler(Looper.getMainLooper())));
    }

    public RequestQueue(Cache cache, Network network, int threadPoolSize,
            ResponseDelivery delivery) {
        mCache = cache;
        mNetwork = network;
        mDispatchers = new NetworkDispatcher[threadPoolSize];
        mDelivery = delivery;
    }

  RequestQueue在初始时,mDelivery保存了ExecutorDelivery对象的引用。并在start方法中,将其传给了,NetworkDispatcher和CacheDispatcher:

    public void start() {
        stop();  // Make sure any currently running dispatchers are stopped.
        // Create the cache dispatcher and start it.
        mCacheDispatcher = new CacheDispatcher(mCacheQueue, mNetworkQueue, mCache, mDelivery);
        mCacheDispatcher.start();

        // Create network dispatchers (and corresponding threads) up to the pool size.
        for (int i = 0; i < mDispatchers.length; i++) {
            NetworkDispatcher networkDispatcher = new NetworkDispatcher(mNetworkQueue, mNetwork,
                    mCache, mDelivery);
            mDispatchers[i] = networkDispatcher;
            networkDispatcher.start();
        }
    }

 

  然后在NetworkDispatcher的run方法的最后:

                mDelivery.postResponse(request, response);
            } catch (VolleyError volleyError) {
                volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs);
                parseAndDeliverNetworkError(request, volleyError);
            } catch (Exception e) {
                VolleyLog.e(e, "Unhandled exception %s", e.toString());
                VolleyError volleyError = new VolleyError(e);
                volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs);
                mDelivery.postError(request, volleyError);
            }

  用postResponse方法,分发请求的响应或是用postError分发错误信息。

 

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

 

  我们来看一看ExecutorDelivery具体的代码:

  先看构造方法:

public class ExecutorDelivery implements ResponseDelivery {
    /** Used for posting responses, typically to the main thread. */
    private final Executor mResponsePoster;

    /**
     * Creates a new response delivery interface.
     * @param handler {@link Handler} to post responses on
     */
    public ExecutorDelivery(final Handler handler) {
        // Make an Executor that just wraps the handler.
        mResponsePoster = new Executor() {
            @Override
            public void execute(Runnable command) {
                handler.post(command);
            }
        };
    }

 

  构造方法中,构建了一个执行器。负责将任务分发出去。  

    @Override
    public void postResponse(Request<?> request, Response<?> response) {
        postResponse(request, response, null);
    }

    @Override
    public void postResponse(Request<?> request, Response<?> response, Runnable runnable) {
        request.markDelivered();
        request.addMarker("post-response");
        mResponsePoster.execute(new ResponseDeliveryRunnable(request, response, runnable));
    }

    @Override
    public void postError(Request<?> request, VolleyError error) {
        request.addMarker("post-error");
        Response<?> response = Response.error(error);
        mResponsePoster.execute(new ResponseDeliveryRunnable(request, response, null));
    }

  这里的实现比较简单,只需要看一下ResponseDeliveryRunnable的实现。

    private class ResponseDeliveryRunnable implements Runnable {
        private final Request mRequest;
        private final Response mResponse;
        private final Runnable mRunnable;

        public ResponseDeliveryRunnable(Request request, Response response, Runnable runnable) {
            mRequest = request;
            mResponse = response;
            mRunnable = runnable;
        }

        @SuppressWarnings("unchecked")
        @Override
        public void run() {
            // If this request has canceled, finish it and don‘t deliver.
            if (mRequest.isCanceled()) {
                mRequest.finish("canceled-at-delivery");
                return;
            }

            // Deliver a normal response or error, depending.
            if (mResponse.isSuccess()) {
                mRequest.deliverResponse(mResponse.result);
            } else {
                mRequest.deliverError(mResponse.error);
            }

            // If this is an intermediate response, add a marker, otherwise we‘re done
            // and the request can be finished.
            if (mResponse.intermediate) {
                mRequest.addMarker("intermediate-response");
            } else {
                mRequest.finish("done");
            }

            // If we have been provided a post-delivery runnable, run it.
            if (mRunnable != null) {
                mRunnable.run();
            }
       }
    }

  我们可以看到,这一段实现中,调用deliverResponse,直接将Response中的result成员传入。

   从这里,我们可以看出,StringRequset.java中的:

    @Override
    protected void deliverResponse(String response) {
        mListener.onResponse(response);
    }

  这里的response就是Response中的result。

 

Done

以上是关于Volley——ExecutorDelivery的主要内容,如果未能解决你的问题,请参考以下文章

volley3--Volley类

Volley源码解析——从实现角度深入剖析volley

深入volley自己来写volley

反应原生找不到 com.android.volley:volley:1.1.1

Volley框架源码分析

Volley-->