殊途同归的execute() 与 enqueue()

execute()

  • 先从 OkHttpClient().newCall().execute() 跟进,可以看到 newCall() 的定义如下:
    • 可以看出,execute() 其实是 RealCall 里面实现的方法,继续跟进 RealCall,此时就可以看到 execute() 的定义代码了:
      • 继续跟进 client.dispatcher.executed(),知道其定义如下:

        enqueue()

        • 同样,也先从 OkHttpClient().newCall(request).enqueue() 跟进,直接看到 OkHttpClient().newCall(request).enqueue() 的定义如下:
          • 再跟进 client.dispatcher.enqueue(),发现其定义如下:
            • 再跟进 promoteAndExecute()
              • 可以看到,不论是 execute() 还是 enqueue(),其实最后都是要把任务压进 runningAsyncCalls 中执行,不同的是,前者是同步压入,而后者是异步压入

              AsyncCall

              • 从上面的代码中,不难看出,execute()enqueue(),最终都是依赖与 AsyncCall 运行的,且 AsyncCall() 继承自 Runnable,这意味着,它必须实现 run() 方法,下面是其定义:
                • 又在 promoteAndExecute() 中,看到有 asyncCall.executeOn(executorService),所以接下来看看 AsyncCall.executeOn() 的定义:

                  getResponseWithInterceptorChain()

                  • 从上面分析已经可以知道,不管是 execute() 还是 enqueue(),都会调用到 getResponseWithInterceptorChain(),所以来看看其定义:
                    • 从上面的定义可以看出,getResponseWithInterceptorChain() 是按一定顺序,构建了一条 责任链,并通过 proceed(request) 返回 Response
                    • 到这里,整个调用流程就算是分析完了,下面来看看其调用流程图。

                    调用流程图

                    notion image
                    notion image

                    参考/推荐

                    OkHttp 基础使用Leetcode_剑指_Offer_42-连续子数组的最大和
                    Loading...