殊途同归的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
- 到这里,整个调用流程就算是分析完了,下面来看看其调用流程图。
调用流程图

参考/推荐
- Author:CoderWdd
- URL:https://www.wuinsights.top//article/1210c5b7c90c
- Copyright:All articles in this blog, except for special statements, adopt BY-NC-SA agreement. Please indicate the source!
Relate Posts