眾所周知洞慎,在現(xiàn)在的Android開(kāi)發(fā)中,針對(duì)與網(wǎng)絡(luò)請(qǐng)求菱皆,Retrofit+okHttp的組合絕對(duì)是不二之選须误,而在網(wǎng)上針對(duì)于Retrofit分析的文章也有很多了,這次我也分享一些閱讀Retrofit源碼的心得仇轻,希望能夠?qū)Υ蠹矣兴鶐椭┝ S捎谖以诠ぷ髦惺褂玫陌姹緸?.1,所以本次也是針對(duì)2.1版本進(jìn)行分析篷店,首先來(lái)看看Retrofit一種簡(jiǎn)單的用法:
Retrofit簡(jiǎn)單使用示例
首先創(chuàng)建出Retrofit對(duì)象祭椰,進(jìn)行相應(yīng)的初始化配置:
retrofit=new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(getClient())
.build();
然后在Service接口中寫(xiě)入相應(yīng)方法,并加上相應(yīng)的注解:
public interface Api {
@GET(apiUrl)
Call<Response> methodName();
}
最后傳入請(qǐng)求的回調(diào)方法Callback就完成了:
retrofit.create(Api.class).methodName().enqueue(Callback);
對(duì)于Retrofit對(duì)象的Build中疲陕,主要的都是對(duì)于參數(shù)的初始化方淤,所以本次就從Retrofit類(lèi)中的create(final Class<T> service)入手
Retrofit.create
public <T> T create(final Class<T> service) {
//api類(lèi)必須為接口,且不能實(shí)現(xiàn)或繼承其他接口鸭轮,否則在動(dòng)態(tài)代理步驟將會(huì)拋出異常
Utils.validateServiceInterface(service);
if (validateEagerly) {
//立即開(kāi)始遍歷調(diào)用service中的所有方法
eagerlyValidateMethods(service);
}
//返回service類(lèi)的動(dòng)態(tài)代理對(duì)象臣淤,當(dāng)調(diào)用service中的方法時(shí),就會(huì)進(jìn)入其中進(jìn)行處理
return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] { service },
new InvocationHandler() {
//獲取當(dāng)前平臺(tái)(Android或Java8)
private final Platform platform = Platform.get();
@Override public Object invoke(Object proxy, Method method, Object... args)
throws Throwable {
// If the method is a method from Object then defer to normal invocation.
// 如果該方法為Class類(lèi)中的方法窃爷,則直接執(zhí)行
if (method.getDeclaringClass() == Object.class) {
return method.invoke(this, args);
}
//判斷給方法是否為default method邑蒋,針對(duì)Android平臺(tái),該值永遠(yuǎn)為false按厘,所以不應(yīng)在Service類(lèi)中加入default方法医吊,經(jīng)嘗試可能會(huì)導(dǎo)致崩潰
//關(guān)于default method可以參考 http://ebnbin.com/2015/12/20/java-8-default-methods/
if (platform.isDefaultMethod(method)) {
return platform.invokeDefaultMethod(method, service, proxy, args);
}
//1.獲取調(diào)用方法的ServiceMethod對(duì)象
ServiceMethod serviceMethod = loadServiceMethod(method);
//2.創(chuàng)建OkHttpCall對(duì)象
OkHttpCall okHttpCall = new OkHttpCall<>(serviceMethod, args);
//3.將上一步生成的OkHttpCall對(duì)象轉(zhuǎn)換為在service中所配置的Call對(duì)象
return serviceMethod.callAdapter.adapt(okHttpCall);
}
});
}
在這段代碼的最后所返回的Call對(duì)象就是用來(lái)使用的Call對(duì)象了。
其中有一個(gè)很有趣的地方逮京,在 Platform 類(lèi)中有一個(gè)通過(guò)判斷特定的類(lèi)是否存在的方式獲取當(dāng)前平臺(tái)的步驟卿堂,在我的2.1版本中有這么一段代碼:
try {
Class.forName("org.robovm.apple.foundation.NSObject");
return new IOS();
} catch (ClassNotFoundException ignored) {}
但在最新的2.3版本中這段代碼已被移除,這說(shuō)明Retrofit在之前版本中有對(duì)IOS平臺(tái)的支持懒棉,但是我在網(wǎng)上卻沒(méi)有找到相關(guān)的資料草描,不知道有沒(méi)有哪位朋友能為我解答一下。
在上面的代碼中策严,重點(diǎn)是最后的三行代碼穗慕,下面就分別對(duì)于這三行代碼進(jìn)分析:
1.ServiceMethod serviceMethod = loadServiceMethod(method);
Retrofit.loadServiceMethod
下面來(lái)通過(guò)loadServiceMethod方法看看ServiceMethod對(duì)象是如何創(chuàng)建出來(lái)的
ServiceMethod loadServiceMethod(Method method) {
ServiceMethod result;
synchronized (serviceMethodCache) {
//該方法的ServiceMethod對(duì)象是否已存在緩存中,如果是妻导,則直接使用緩存中的對(duì)象
result = serviceMethodCache.get(method);
if (result == null) {
//創(chuàng)建ServiceMethod對(duì)象并將其放入緩存
result = new ServiceMethod.Builder(this, method).build();
serviceMethodCache.put(method, result);
}
}
return result;
}
在代碼中可以看出創(chuàng)建ServiceMethod對(duì)象主要都在ServiceMethod.Builder之中
在其中我發(fā)現(xiàn)了一點(diǎn)逛绵,在我所使用的2.1版本中怀各,作為緩存使用的serviceMethodCache為L(zhǎng)inkedHashMap,但在最新的2.3版本中已被換成了線(xiàn)程安全的ConcurrentHashMap术浪。
ServiceMethod.Builder.Builder
首先看看Build中的構(gòu)造方法:
public Builder(Retrofit retrofit, Method method) {
this.retrofit = retrofit; //retrofit對(duì)象
this.method = method; //所調(diào)用的方法
this.methodAnnotations = method.getAnnotations(); //方法上的注解
this.parameterTypes = method.getGenericParameterTypes(); //方法中參數(shù)的類(lèi)型
this.parameterAnnotationsArray = method.getParameterAnnotations(); //方法中參數(shù)上的注解
}
可以看出瓢对,構(gòu)造方法中的代碼很簡(jiǎn)單,就是針對(duì)各個(gè)變量的賦值操作胰苏。下面就是ServiceMethod中的重頭戲硕蛹,也就是build方法,對(duì)于注解的解析也都是在這里完成的硕并,這一部分的代碼雖多妓美,但是大部分都是對(duì)于注解的解析與異常的判斷,還是一樣先來(lái)看看代碼:
ServiceMethod.Builder.build
public ServiceMethod build() {
//代碼中將略去其中的合法性檢測(cè)部分
//通過(guò)retrofit中的CallAdapterFactory生成CallAdapter鲤孵,用以生成網(wǎng)絡(luò)請(qǐng)求所需的執(zhí)行器
callAdapter = createCallAdapter();
//數(shù)據(jù)數(shù)據(jù)轉(zhuǎn)換工廠(chǎng)壶栋,例如常用的GsonConverterFactory
responseConverter = createResponseConverter();
//解析方法上的注解
for (Annotation annotation : methodAnnotations) {
parseMethodAnnotation(annotation);
}
//解析方法中各參數(shù)上的注解
int parameterCount = parameterAnnotationsArray.length;
parameterHandlers = new ParameterHandler<?>[parameterCount];
for (int p = 0; p < parameterCount; p++) {
Type parameterType = parameterTypes[p];
Annotation[] parameterAnnotations = parameterAnnotationsArray[p];
parameterHandlers[p] = parseParameter(p, parameterType, parameterAnnotations);
}
//返回ServiceMethod對(duì)象
return new ServiceMethod<>(this);
}
其中最重要的應(yīng)該是屬于對(duì)于方法與參數(shù)的注解解析的部分了,這也是Retrofit的特色之一普监,先來(lái)看看對(duì)于方法部分的注解解析:
ServiceMethod.parseMethodAnnotation
private void parseMethodAnnotation(Annotation annotation) {
//除去異常判斷后的代碼
if (annotation instanceof DELETE) {
parseHttpMethodAndPath("DELETE", ((DELETE) annotation).value(), false);
} else if (annotation instanceof GET) {
parseHttpMethodAndPath("GET", ((GET) annotation).value(), false);
} else if (annotation instanceof HEAD) {
parseHttpMethodAndPath("HEAD", ((HEAD) annotation).value(), false);
} else if (annotation instanceof PATCH) {
parseHttpMethodAndPath("PATCH", ((PATCH) annotation).value(), true);
} else if (annotation instanceof POST) {
parseHttpMethodAndPath("POST", ((POST) annotation).value(), true);
} else if (annotation instanceof PUT) {
parseHttpMethodAndPath("PUT", ((PUT) annotation).value(), true);
} else if (annotation instanceof OPTIONS) {
parseHttpMethodAndPath("OPTIONS", ((OPTIONS) annotation).value(), false);
} else if (annotation instanceof HTTP) {
HTTP http = (HTTP) annotation;
parseHttpMethodAndPath(http.method(), http.path(), http.hasBody());
} else if (annotation instanceof retrofit2.http.Headers) {
String[] headersToParse = ((retrofit2.http.Headers) annotation).value();
headers = parseHeaders(headersToParse);
} else if (annotation instanceof Multipart) {
isMultipart = true;
} else if (annotation instanceof FormUrlEncoded) {
isFormEncoded = true;
}
}
可以看出來(lái)贵试,這個(gè)方法中的邏輯很簡(jiǎn)單,主要是判斷出注解的類(lèi)型凯正,并將對(duì)應(yīng)的字符串傳入之后的處理中毙玻,真正的處理還是在parseHttpMethodAndPath與parseHeaders兩個(gè)方法中
ServiceMethod.parseHttpMethodAndPath
private void parseHttpMethodAndPath(String httpMethod, String value, boolean hasBody) {
//除去異常判斷后的代碼
//方法的類(lèi)型(如GET,POST廊散,PUT等)
this.httpMethod = httpMethod;
//是否含有Body
this.hasBody = hasBody;
//判斷相對(duì)路徑是否為空
if (value.isEmpty()) {
return;
}
//將相對(duì)路徑
this.relativeUrl = value;
//解析相對(duì)路徑中的參數(shù)
this.relativeUrlParamNames = parsePathParameters(value);
}
在除去其中異常判斷后桑滩,這個(gè)方法的邏輯就變得非常清晰了
ServiceMethod.parsePathParameters
static Set<String> parsePathParameters(String path) {
// PARAM_URL_REGEX = \{([a-zA-Z][a-zA-Z0-9_-]*)\}
Matcher m = PARAM_URL_REGEX.matcher(path);
Set<String> patterns = new LinkedHashSet<>();
while (m.find()) {
patterns.add(m.group(1));
}
return patterns;
}
這個(gè)方法也很好理解,使用正則表達(dá)式匹配出相對(duì)路徑中以"{}"包裹的變量允睹,然后放入Set集合中
ServiceMethod.parseHeaders
該方法的作用為Header注解的解析:
private Headers parseHeaders(String[] headers) {
Headers.Builder builder = new Headers.Builder();
for (String header : headers) {
//解析出header中的key和value
int colon = header.indexOf(':');
String headerName = header.substring(0, colon);
String headerValue = header.substring(colon + 1).trim();
//針對(duì)Content-type的頭运准,將其存入contentType變量中
if ("Content-Type".equalsIgnoreCase(headerName)) {
MediaType type = MediaType.parse(headerValue);
contentType = type;
} else {
builder.add(headerName, headerValue);
}
}
//創(chuàng)建Headers對(duì)象
return builder.build();
}
ServiceMethod.parseParameterAnnotation
這個(gè)方法用于參數(shù)注解的解析
private ParameterHandler<?> parseParameterAnnotation(
int p, Type type, Annotation[] annotations, Annotation annotation) {
if (annotation instanceof Url) {
//do something
} else if (annotation instanceof Path) {
//do something
} else if (annotation instanceof Query) {
//do something
} else if (annotation instanceof QueryMap) {
//do something
} else if (annotation instanceof Header) {
//do something
} else if (annotation instanceof HeaderMap) {
//do something
} else if (annotation instanceof Field) {
//do something
} else if (annotation instanceof FieldMap) {
//do something
} else if (annotation instanceof Part) {
//do something
} else if (annotation instanceof PartMap) {
gotPart = true;
//do something
} else if (annotation instanceof Body) {
//do something
}
return null; // Not a Retrofit annotation.
}
parseParameterAnnotation這個(gè)方法中的代碼雖然多,但是在簡(jiǎn)化之后可以看出來(lái)缭受,就是針對(duì)不同的參數(shù)類(lèi)型進(jìn)行不同的處理然后返回相應(yīng)的ParameterHandler對(duì)象胁澳,因?yàn)槠渲嗅槍?duì)各個(gè)類(lèi)型參數(shù)的處理比較繁瑣,就不一一列舉了米者。
需要提到的是韭畸,在這個(gè)方法中,有一個(gè)類(lèi)的出現(xiàn)頻率非常的高蔓搞,這就是ParameterHandler類(lèi)胰丁,這個(gè)類(lèi)的主要作用是將注解中的各項(xiàng)參數(shù)通過(guò)RequestBuilder類(lèi)轉(zhuǎn)換為okHttp中使用的Request。
2.OkHttpCall okHttpCall = new OkHttpCall<>(serviceMethod, args);
在OkHttpCall類(lèi)中喂分,最主要的就是execute與enqueue兩個(gè)方法锦庸,分別為同步與異步的網(wǎng)絡(luò)請(qǐng)求,但是需要注意的是妻顶,這兩個(gè)方法并不是我們?cè)谑褂弥兴{(diào)用的方法酸员,真正提供給外界調(diào)用的方法,會(huì)在文章之后的部分講到讳嘱。
OkHttpCall.execute
@Override public Response<T> execute() throws IOException {
//okHttp中的call對(duì)象幔嗦,由于本次分析限于Retrofit中,所以不做深究
okhttp3.Call call;
synchronized (this) {
//一個(gè)OkhttpCall對(duì)象只能執(zhí)行一次網(wǎng)絡(luò)請(qǐng)求
if (executed) throw new IllegalStateException("Already executed.");
executed = true;
//省略部分異常判斷代碼
call = rawCall;
if (call == null) {
try {
//如果okHttp對(duì)象未創(chuàng)建沥潭,則在創(chuàng)建后賦值給變量call
call = rawCall = createRawCall();
} catch (IOException | RuntimeException e) {
creationFailure = e;
throw e;
}
}
}
//防止當(dāng)調(diào)用過(guò)cancel方法后新創(chuàng)建的Call未被cancel的情況
if (canceled) {
call.cancel();
}
//使用okhttp開(kāi)始執(zhí)行網(wǎng)絡(luò)請(qǐng)求
return parseResponse(call.execute());
}
OkHttpCall.enqueue
@Override public void enqueue(final Callback<T> callback) {
if (callback == null) throw new NullPointerException("callback == null");
//okHttp中的call對(duì)象邀泉,由于本次分析限于Retrofit中,所以不做深究
okhttp3.Call call;
Throwable failure;
//一個(gè)OkhttpCall對(duì)象只能執(zhí)行一次網(wǎng)絡(luò)請(qǐng)求
synchronized (this) {
if (executed) throw new IllegalStateException("Already executed.");
executed = true;
call = rawCall;
failure = creationFailure;
if (call == null && failure == null) {
try {
//如果okHttp對(duì)象未創(chuàng)建钝鸽,則在創(chuàng)建后賦值給變量call
call = rawCall = createRawCall();
} catch (Throwable t) {
failure = creationFailure = t;
}
}
}
//創(chuàng)建okhttp對(duì)象失敗時(shí)汇恤,直接進(jìn)行Fail的回調(diào)方法
if (failure != null) {
callback.onFailure(this, failure);
return;
}
//防止當(dāng)調(diào)用過(guò)cancel方法后新創(chuàng)建的Call未被cancel的情況
if (canceled) {
call.cancel();
}
//使用okhttp開(kāi)始執(zhí)行網(wǎng)絡(luò)請(qǐng)求,并針對(duì)返回結(jié)果調(diào)用Callback中相應(yīng)的回調(diào)方法
call.enqueue(new okhttp3.Callback() {
@Override public void onResponse(okhttp3.Call call, okhttp3.Response rawResponse)
throws IOException {
Response<T> response;
try {
response = parseResponse(rawResponse);
} catch (Throwable e) {
callFailure(e);
return;
}
callSuccess(response);
}
@Override public void onFailure(okhttp3.Call call, IOException e) {
try {
callback.onFailure(OkHttpCall.this, e);
} catch (Throwable t) {
t.printStackTrace();
}
}
private void callFailure(Throwable e) {
try {
callback.onFailure(OkHttpCall.this, e);
} catch (Throwable t) {
t.printStackTrace();
}
}
private void callSuccess(Response<T> response) {
try {
callback.onResponse(OkHttpCall.this, response);
} catch (Throwable t) {
t.printStackTrace();
}
}
});
}
enqueue方法在主要的邏輯上拔恰,與上面的execute是基本相同的因谎,但是有一點(diǎn)需要注意,就是當(dāng)收到Response時(shí)并不會(huì)馬上進(jìn)行Callback中的onResponse回調(diào)颜懊,而是會(huì)調(diào)用parseResponse方法對(duì)返回的Response進(jìn)行一次解析财岔,如果解析中出現(xiàn)了異常,依然會(huì)進(jìn)行onFailure的回調(diào)方法河爹。
OkHttpCall.parseResponse
Response<T> parseResponse(okhttp3.Response rawResponse) throws IOException {
// 取出Response中的Body
ResponseBody rawBody = rawResponse.body();
// 這個(gè)變量就是最后獲得的Response中的rawResponse匠璧,這實(shí)際上是一個(gè)在請(qǐng)求中返回的,去除了body部分的okhttp.Response原始對(duì)象
// 移除okhttp3.Response中的Source部分并重建一個(gè)okhttp.Response對(duì)象
// Remove the body's source (the only stateful object) so we can pass the response along.
rawResponse = rawResponse.newBuilder()
.body(new NoContentResponseBody(rawBody.contentType(), rawBody.contentLength()))
.build();
int code = rawResponse.code();
//如果code不在200~299的范圍內(nèi)咸这,則代表請(qǐng)求異常
if (code < 200 || code >= 300) {
try {
// Buffer the entire body to avoid future I/O.
ResponseBody bufferedBody = Utils.buffer(rawBody);
return Response.error(bufferedBody, rawResponse);
} finally {
rawBody.close();
}
}
// 204 NO CONTENT 與 205 RESET CONTENT 兩個(gè)code是不含有body的
// 具體可以查閱https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204與
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/205
if (code == 204 || code == 205) {
return Response.success(null, rawResponse);
}
// ExceptionCatchingRequestBody是為了捕獲在解析rawBody中的內(nèi)容的buffer時(shí)拋出的異常
ExceptionCatchingRequestBody catchingBody = new ExceptionCatchingRequestBody(rawBody);
try {
// 通過(guò)Converter(如:GsonResponseBodyConverter)將Response中的流解析為所需的返回類(lèi)型
T body = serviceMethod.toResponse(catchingBody);
return Response.success(body, rawResponse);
} catch (RuntimeException e) {
// If the underlying source threw an exception, propagate that rather than indicating it was
// a runtime exception.
catchingBody.throwIfCaught();
throw e;
}
}
這個(gè)方法主要是對(duì)okhttp中返回的response進(jìn)行一次解析夷恍,對(duì)其進(jìn)行一些預(yù)處理,并將其轉(zhuǎn)換為更易于使用的Response對(duì)象
OkHttpCall.createRawCall
private okhttp3.Call createRawCall() throws IOException {
//獲取ServiceMethod生成的Request對(duì)象
Request request = serviceMethod.toRequest(args);
//通過(guò)callFactory將Request轉(zhuǎn)換為Okhttp3.Call
okhttp3.Call call = serviceMethod.callFactory.newCall(request);
if (call == null) {
throw new NullPointerException("Call.Factory returned null.");
}
return call;
}
這個(gè)方法主要用于創(chuàng)建okHttp中的Call對(duì)象媳维,邏輯非常簡(jiǎn)單酿雪,就不多做分析了
3.serviceMethod.callAdapter.adapt(okHttpCall)
這個(gè)方法實(shí)際是使用在創(chuàng)建Retrofit對(duì)象時(shí)傳入的CallAdapterFactory將OkHttpCall對(duì)象轉(zhuǎn)換為最后使用所需的對(duì)象,Retrofit中會(huì)默認(rèn)配置一個(gè)ExecutorCallAdapterFactory侄刽,除此之外還有常用的RxJavaCallAdapterFactory與一個(gè)最簡(jiǎn)單的DefaultCallAdapterFactory执虹。我們抽取出其中的adapt方法來(lái)看一看:
DefaultCallAdapterFactory
final class DefaultCallAdapterFactory extends CallAdapter.Factory {
//DefaultCallAdapterFactory在返回時(shí)為一個(gè)單例對(duì)象
static final CallAdapter.Factory INSTANCE = new DefaultCallAdapterFactory();
//構(gòu)造方法
@Override
public CallAdapter<?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
if (getRawType(returnType) != Call.class) {
return null;
}
final Type responseType = Utils.getCallResponseType(returnType);
return new CallAdapter<Call<?>>() {
//獲取返回值的類(lèi)型
@Override public Type responseType() {
return responseType;
}
//將傳入的Call對(duì)象轉(zhuǎn)換為最后處理所需要的對(duì)象返回,在DefaultCallAdapterFactory中為將傳入其中的對(duì)象直接返回
@Override public <R> Call<R> adapt(Call<R> call) {
return call;
}
};
}
}
這個(gè)是Retrofit中最為基本的CallAdapter唠梨,也只有在平臺(tái)為Java8或者無(wú)法判斷平臺(tái)時(shí)才會(huì)使用袋励,也由于這個(gè)類(lèi)的邏輯非常簡(jiǎn)單,也可以通過(guò)這個(gè)類(lèi)了解到CallAdapter.Factory最核心的兩個(gè)方法的作用
ExecutorCallAdapterFactory
ExecutorCallAdapterFactory類(lèi)為Android平臺(tái)的默認(rèn)CallAdapter:
final class ExecutorCallAdapterFactory extends CallAdapter.Factory {
final Executor callbackExecutor;
//構(gòu)造方法
ExecutorCallAdapterFactory(Executor callbackExecutor) {
this.callbackExecutor = callbackExecutor;
}
//獲取CallAdapter對(duì)象
@Override
public CallAdapter<Call<?>> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
if (getRawType(returnType) != Call.class) {
return null;
}
final Type responseType = Utils.getCallResponseType(returnType);
return new CallAdapter<Call<?>>() {
//獲取返回參數(shù)的類(lèi)型
@Override public Type responseType() {
return responseType;
}
//將傳入的Call對(duì)象轉(zhuǎn)換為最后處理所需要的對(duì)象返回,在這里的返回類(lèi)型為內(nèi)部類(lèi)ExecutorCallbackCall
@Override public <R> Call<R> adapt(Call<R> call) {
return new ExecutorCallbackCall<>(callbackExecutor, call);
}
};
}
//這就是在ExecutorCallAdapterFactory中返回給外界去使用的對(duì)象当叭,也就是在文章開(kāi)頭調(diào)用了相應(yīng)的api方法后所返回的對(duì)象
static final class ExecutorCallbackCall<T> implements Call<T> {
final Executor callbackExecutor;
final Call<T> delegate;
ExecutorCallbackCall(Executor callbackExecutor, Call<T> delegate) {
this.callbackExecutor = callbackExecutor;
this.delegate = delegate;
}
//在文章開(kāi)頭的使用示例中所傳入的CallBack實(shí)際就是在這里調(diào)用相應(yīng)的回調(diào)方法
@Override public void enqueue(final Callback<T> callback) {
if (callback == null) throw new NullPointerException("callback == null");
delegate.enqueue(new Callback<T>() {
@Override public void onResponse(Call<T> call, final Response<T> response) {
//這里的callbackExecutor來(lái)源于針對(duì)當(dāng)前平臺(tái)的對(duì)象Platform中的defaultCallbackExecutor方法
//在Android平臺(tái)中茬故,該方法的返回語(yǔ)句為 return new MainThreadExecutor();
//MainThreadExecutor的實(shí)現(xiàn)為通過(guò)handler將Runnable對(duì)象發(fā)送至主線(xiàn)程執(zhí)行
callbackExecutor.execute(new Runnable() {
@Override public void run() {
if (delegate.isCanceled()) {
// Emulate OkHttp's behavior of throwing/delivering an IOException on cancellation.
callback.onFailure(ExecutorCallbackCall.this, new IOException("Canceled"));
} else {
callback.onResponse(ExecutorCallbackCall.this, response);
}
}
});
}
@Override public void onFailure(Call<T> call, final Throwable t) {
//此處callbackExecutor作用同上
callbackExecutor.execute(new Runnable() {
@Override public void run() {
callback.onFailure(ExecutorCallbackCall.this, t);
}
});
}
});
}
//do something
}
結(jié)語(yǔ)
那么,到現(xiàn)在為止蚁鳖,我們簡(jiǎn)單梳理了Retrofit中的Call的創(chuàng)建流程與ServiceMethod類(lèi)中的主要邏輯磺芭,而這些,也只是Retrofi中的一部分而已醉箕,而我也是第一次寫(xiě)這樣的文章钾腺,加上我的技術(shù)還不到位徙垫,所以肯定會(huì)有很多的不足,歡迎大家來(lái)批評(píng)指正放棒。