1 简介
提供给使用者的接口类:Retrofit
Retrofit用注解的方式为HTTP接口适配了带有回调的java接口,通过这些java接口可以实现HTTP请求。
本文Retrofit版本:2.6.0
2 Retrofit组成:
2.1 Builder: Retrofit构建器(Builder模式)
作用:在保证Retrofit有默认组件的情况下,方便使用者自定义相关Retrofit组件。
小细节Platform:
Builder也可以配置Platform,默认情况下,Bulder会自动获取对应的平台。
private static Platform findPlatform() {
try {
Class.forName("android.os.Build");
if (Build.VERSION.SDK_INT != 0) {
return new Android();
}
} catch (ClassNotFoundException ignored) {
}
try {
Class.forName("java.util.Optional");
return new Java8();
} catch (ClassNotFoundException ignored) {
}
return new Platform();
}
可以看到有三个平台,Android(继承Platform),Java8(继承Platform)和Platform自己。
下面再看三个平台区别:
2.1.1 Platform
Platform平台应该是用来支持java8版本之下的java平台。
class Platform {
...
// 平台无回调执行器,应该在哪里创建的,就在哪里回调
Executor defaultCallbackExecutor() {
return null;
}
// 平台默认的回调适配器工厂列表为new DefaultCallAdapterFactory(callbackExecutor)
List extends CallAdapter.Factory> defaultCallAdapterFactories(
@Nullable Executor callbackExecutor) {
return singletonList(new DefaultCallAdapterFactory(callbackExecutor));
}
// 默认回调适配器工厂数量为1
int defaultCallAdapterFactoriesSize() {
return 1;
}
// 默认的转换器工厂列表为空列表
List extends Converter.Factory> defaultConverterFactories() {
return emptyList();
}
// 是否是默认方法
boolean isDefaultMethod(Method method) {
return false;
}
// 调用指定类默认的方法会抛异常,即不支持调用非默认方法
@Nullable Object invokeDefaultMethod(Method method, Class> declaringClass, Object object,
@Nullable Object... args) throws Throwable {
throw new UnsupportedOperationException();
}
...
}
- isDefaultMethod()返回false,表示传入的Method都告知不是默认方法(默认方法是一种公共的非抽象实例方法,即带有主体的非静态方法,在接口中声明)
- invokeDefaultMethod返回异常,表示调用非默认方法不支持
2.1.2 Android
static class Android extends Platform {
// 平台默认的回调执行器 可以看出默认的回调线程是UI线程,所以使用者不用在回调里做线程切换
@Override public Executor defaultCallbackExecutor() {
return new MainThreadExecutor();
}
// 是否是默认方法
@Override boolean isDefaultMethod(Method method) {
// 如果安卓构建版本小于24(安卓7.0),则直接返回是非默认方法,否则正常返回method.isDefault()
if (Build.VERSION.SDK_INT < 24) {
return false;
}
return method.isDefault();
}
//回调执行器必须不为空,回调适配器工厂列表版本小于Android7返回new DefaultCallAdapterFactory(callbackExecutor)单独组成的不可变list,否则返回CompletableFutureCallAdapterFactory.INSTANCE和DefaultCallAdapterFactory(callbackExecutor)组成的不可变list
@Override List extends CallAdapter.Factory> defaultCallAdapterFactories(
@Nullable Executor callbackExecutor) {
if (callbackExecutor == null) throw new AssertionError();
DefaultCallAdapterFactory executorFactory = new DefaultCallAdapterFactory(callbackExecutor);
// CompletableFutureCallAdapterFactory是支持CompletableFutureCall,是java8特性
return Build.VERSION.SDK_INT >= 24
? asList(CompletableFutureCallAdapterFactory.INSTANCE, executorFactory)
: singletonList(executorFactory);
}
// 默认的回调适配器工程个数,和defaultCallAdapterFactories对应
@Override int defaultCallAdapterFactoriesSize() {
return Build.VERSION.SDK_INT >= 24 ? 2 : 1;
}
// 默认的转换器工厂
@Override List extends Converter.Factory> defaultConverterFactories() {
// 如果平台支持java8,则让Converter支持java8操作符
return Build.VERSION.SDK_INT >= 24
? singletonList(OptionalConverterFactory.INSTANCE)
: Collections.emptyList();
}
// 默认转换器工厂个数
@Override int defaultConverterFactoriesSize() {
return Build.VERSION.SDK_INT >= 24 ? 1 : 0;
}
//安卓平台的主线程执行器
static class MainThreadExecutor implements Executor {
private final Handler handler = new Handler(Looper.getMainLooper());
@Override public void execute(Runnable r) {
handler.post(r);
}
}
}
Android有默认的MainThreadExecutor,就是Android主线程任务执行器,默认的CallAdapter.Factory任务回调适配器工厂。
从这里就可以看出Android平台上,Retrofit执行任务默认是在主线程。
2.1.3 java8
static class Java8 extends Platform {
// 默认method.isDefault()
@Override boolean isDefaultMethod(Method method) {
return method.isDefault();
}
// 支持调用默认方法
@Override Object invokeDefaultMethod(Method method, Class> declaringClass, Object object,
@Nullable Object... args) throws Throwable {
// Because the service interface might not be public, we need to use a MethodHandle lookup
// that ignores the visibility of the declaringClass.
Constructor constructor = Lookup.class.getDeclaredConstructor(Class.class, int.class);
constructor.setAccessible(true);
return constructor.newInstance(declaringClass, -1 /* trusted */)
.unreflectSpecial(method, declaringClass)
.bindTo(object)
.invokeWithArguments(args);
}
// 默认适配器工厂列表,和Android差不多
@Override List extends CallAdapter.Factory> defaultCallAdapterFactories(
@Nullable Executor callbackExecutor) {
List factories = new ArrayList<>(2);
factories.add(CompletableFutureCallAdapterFactory.INSTANCE);
factories.add(new DefaultCallAdapterFactory(callbackExecutor));
return unmodifiableList(factories);
}
// 默认适配器工厂个数
@Override int defaultCallAdapterFactoriesSize() {
return 2;
}
// 默认转换器工厂列表
@Override List extends Converter.Factory> defaultConverterFactories() {
return singletonList(OptionalConverterFactory.INSTANCE);
}
// 默认转换器工厂个数
@Override int defaultConverterFactoriesSize() {
return 1;
}
}
- isDefaultMethod():返回method.isDefault()
- invokeDefaultMethod():调用非默认方法接口。
总结一下:
平台 | 默认回调执行器 | 默认回调适配器工厂 | 默认转换器工厂 | 判断methos是默认方法 | Object invokeDefaultMethod() |
---|---|---|---|---|---|
Platform | 无 | DefaultCallAdapterFactory(callbackExecutor) | 无 | false | 不支持 |
Java8 | 无 | DefaultCallAdapterFactory(callbackExecutor)和CompletableFutureCallAdapterFactory.INSTANCE | OptionalConverterFactory.INSTANCE | method.isDefault() | 支持 |
Android | MainThreadExecutor | 一个DefaultCallAdapterFactory(callbackExecutor)或者DefaultCallAdapterFactory(callbackExecutor)和CompletableFutureCallAdapterFactory.INSTANCE | OptionalConverterFactory.INSTANCE | SDK_INT< 24 ? false:method.isDefault() | 不支持 |
2.2 合成Retrofit的组件:
Retrofit是一个门面,这个门面通过组合各种组件来为使用者提供API。以下就是合成Retrofit的必要组件:
-
callFactory:okhttp3.Call.Factory
生成(HTTP调用对象)的工厂 -
baseUrl:HttpUrl
HTTP url相关 converterFactories:List
adapterFactories:List
callbackExecutor: Executor
validateEagerly: boolean
2.2.1 okhttp3.Call.Factory
http调用(call)工厂,就是生产http调用对象的工厂
可以看看okhttp3.Call接口
// 表示单个请求/响应,不能执行两次,它是可以取消的。
public interface Call extends Cloneable {
// 返回发起请求回调的Request
Request request();
// 同步执行
Response execute() throws IOException;
// 异步执行
void enqueue(Callback responseCallback);
// 取消
void cancel();
// 是否已执行
boolean isExecuted();
// 是否已取消
boolean isCanceled();
// 克隆方法
Call clone();
// 工厂接口
interface Factory {
// 工厂方法
Call newCall(Request request);
}
}
如果你使用过OkHttp3,会发现这就是OkHttp3常用的外部接口。所以OkHttpClient就是它的一个实现。所以Retrofit框架里没有自己扩展Call.Factory,那么默认工厂就是用的OkHttp3框架里实现的OkHttpClient。
okhttp3.Call.Factory callFactory = this.callFactory;
if (callFactory == null) {
callFactory = new OkHttpClient();
}
上面取自Retrofit.Builder.build()里的代码,可以看到如果用户没有指定自定义的okhttp3.Call.Factory,那么默认就是用OkHttpClient。
2.2.2 baseUrl:HttpUrl
HttpUrl对象可通过HttpUrl.Build对象的parse()方法构造。HttpUrl包含一个Http Url的组成信息,比如域名,端口,用户名,密码等都可以设置。
HttpUrl就是Retrofit的基地址,它可以通过HttpUrl.parse(String baseUrl)的匹配校验生成一个HttpUrl对象。
例:
/**
* Set the API base URL.
*
* @see #baseUrl(HttpUrl)
*/
public Builder baseUrl(String baseUrl) {
checkNotNull(baseUrl, "baseUrl == null");
return baseUrl(HttpUrl.get(baseUrl));
}
public Builder baseUrl(HttpUrl baseUrl) {
checkNotNull(baseUrl, "baseUrl == null");
List pathSegments = baseUrl.pathSegments();
if (!"".equals(pathSegments.get(pathSegments.size() - 1))) {
throw new IllegalArgumentException("baseUrl must end in /: " + baseUrl);
}
this.baseUrl = baseUrl;
return this;
}
上面取自Retrofit.Builder.build()里的代码,可以得知我们通常set的地址,最后会转化成一个HttpUrl对象。
2.2.3 converterFactories:List
Converter是从一个对象转为另一种对象过程的抽象,简明一点就叫转换器。比如说你总要把用户的请求信息转为OkHttp标准的请求结构(Request),或者是OkHttp的标准响应信息(Response)转为用户数据。
把它抽象为一个接口,接口里就有一个convert方法
public interface Converter {
// T是目标类型,F是原始类型
T convert(F value) throws IOException;
}
然而Converter又可以是多种多样的,这样就最好是用工厂类来生产:
abstract class Factory {
// 生产responseBody转换器
public @Nullable Converter responseBodyConverter(Type type,
Annotation[] annotations, Retrofit retrofit) {
return null;
}
// 目标为RequestBody的转换器 type为原始类型的type,parameterAnnotations为参数上的注解(因为支持Body,Part,PartMap注解),methodAnnotations为方法注解,retrofit是门面
public @Nullable Converter, RequestBody> requestBodyConverter(Type type,
Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
return null;
}
// 生产目标为String类型的转换器
public @Nullable Converter, String> stringConverter(Type type, Annotation[] annotations,
Retrofit retrofit) {
return null;
}
// 泛型参数type的指定位置参数的上限,比如Map extends String,Long>这个type索引位置0参数的type的上限为String,1为Long
protected static Type getParameterUpperBound(int index, ParameterizedType type) {
return Utils.getParameterUpperBound(index, type);
}
// 一般用于获取泛型参数前的type,比如List会返回List.class
protected static Class> getRawType(Type type) {
return Utils.getRawType(type);
}
}
想要转换肯定要知道原始类型和目标类型,所以可以从生成方法中的参数
Retrofit库已经为我们实现了很多Converter,如下图:
常用的GsonConverterFactory实现:
public final class GsonConverterFactory extends Converter.Factory {
// 实例化一个GsonConverterFactory
public static GsonConverterFactory create() {
return create(new Gson());
}
public static GsonConverterFactory create(Gson gson) {
if (gson == null) throw new NullPointerException("gson == null");
return new GsonConverterFactory(gson);
}
private final Gson gson;
// 构造方法
private GsonConverterFactory(Gson gson) {
this.gson = gson;
}
// 把ResponseBody转为指定类型对象
@Override
public Converter responseBodyConverter(Type type, Annotation[] annotations,
Retrofit retrofit) {
TypeAdapter> adapter = gson.getAdapter(TypeToken.get(type));
return new GsonResponseBodyConverter<>(gson, adapter);
}
// 把指定类型转为RequestBody
@Override
public Converter, RequestBody> requestBodyConverter(Type type,
Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
TypeAdapter> adapter = gson.getAdapter(TypeToken.get(type));
return new GsonRequestBodyConverter<>(gson, adapter);
}
}
Gson是怎么解析的?
GsonRequestBodyConverter类里:
// 这里实际也就是把对象转为Json字符串写入到RequestBody里而已。
@Override public RequestBody convert(T value) throws IOException {
Buffer buffer = new Buffer();
Writer writer = new OutputStreamWriter(buffer.outputStream(), UTF_8);
JsonWriter jsonWriter = gson.newJsonWriter(writer);
adapter.write(jsonWriter, value);
jsonWriter.close();
return RequestBody.create(MEDIA_TYPE, buffer.readByteString());
}
使用Gson的jsonWriter配合TypeAdapter写入Buffer,然后构造RequestBody。
GsonResponseBodyConverter
final class GsonResponseBodyConverter implements Converter {
private final Gson gson;
private final TypeAdapter adapter;
GsonResponseBodyConverter(Gson gson, TypeAdapter adapter) {
this.gson = gson;
this.adapter = adapter;
}
// 就是把body里面的Json字符串读出来然后转为指定类型的对象
@Override public T convert(ResponseBody value) throws IOException {
JsonReader jsonReader = gson.newJsonReader(value.charStream());
try {
T result = adapter.read(jsonReader);
if (jsonReader.peek() != JsonToken.END_DOCUMENT) {
throw new JsonIOException("JSON document was not fully consumed.");
}
return result;
} finally {
value.close();
}
}
}
2.2.4 adapterFactories:List 适配器工厂
功能:将默认的网络请求执行器(OkHttpCall)转换成适合被不同平台来调用的网络请求执行器形式,相当于返回一个代理。
CallAdapter.java
// R为原始响应Java对象类型,T为目标响应类型
public interface CallAdapter {
// 返回想要响应转成的Java对象类型
Type responseType();
// 返回一个call的代理
T adapt(Call call);
}
对应的工厂类:其实跟前面的转换器差不多
abstract class Factory {
// 返回一个回调适配器
public abstract @Nullable CallAdapter, ?> get(Type returnType, Annotation[] annotations,
Retrofit retrofit);
// 获取容器指定索引位置的存放值类型
protected static Type getParameterUpperBound(int index, ParameterizedType type) {
return Utils.getParameterUpperBound(index, type);
}
// 获取原始Class
protected static Class> getRawType(Type type) {
return Utils.getRawType(type);
}
}
}
同样的Retrofit也为我们实现了几个现成的适配器工厂
DefaultCallAdapterFactory 默认的Call适配器工厂
重写get():
@Override public @Nullable CallAdapter, ?> get(
Type returnType, Annotation[] annotations, Retrofit retrofit) {
// 若返回类型Type不是Call.class,返回适配器null
if (getRawType(returnType) != Call.class) {
return null;
}
// 返回类型Type必须为带泛型参数的Type
if (!(returnType instanceof ParameterizedType)) {
throw new IllegalArgumentException(
"Call return type must be parameterized as Call or Call extends Foo>");
}
// 取得返回类型的泛型参数第一个参数的Type实例
final Type responseType = Utils.getParameterUpperBound(0, (ParameterizedType) returnType);
// 获取回调执行器
final Executor executor = Utils.isAnnotationPresent(annotations, SkipCallbackExecutor.class)
? null
: callbackExecutor;
return new CallAdapter
扩展Call:代替原来的call,将原call的一些方法放在指定的执行器执行
static final class ExecutorCallbackCall implements Call {
// 回调执行器
final Executor callbackExecutor;
// 我理解为原始call,但不知道这里为什么要命名为delegate,获取是把原对象看作代理吧
final Call delegate;
ExecutorCallbackCall(Executor callbackExecutor, Call delegate) {
this.callbackExecutor = callbackExecutor;
this.delegate = delegate;
}
@Override public void enqueue(final Callback callback) {
checkNotNull(callback, "callback == null");
delegate.enqueue(new Callback() {
@Override public void onResponse(Call call, final Response response) {
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 call, final Throwable t) {
callbackExecutor.execute(new Runnable() {
@Override public void run() {
callback.onFailure(ExecutorCallbackCall.this, t);
}
});
}
});
}
@Override public boolean isExecuted() {
return delegate.isExecuted();
}
@Override public Response execute() throws IOException {
return delegate.execute();
}
@Override public void cancel() {
delegate.cancel();
}
@Override public boolean isCanceled() {
return delegate.isCanceled();
}
@SuppressWarnings("CloneDoesntCallSuperClone") // Performing deep clone.
@Override public Call clone() {
return new ExecutorCallbackCall<>(callbackExecutor, delegate.clone());
}
@Override public Request request() {
return delegate.request();
}
}
CompletableFutureCallAdapterFactory 支持转为ompletableFuture<>的Call适配器工厂
重写get():
@Override public @Nullable CallAdapter, ?> get(
Type returnType, Annotation[] annotations, Retrofit retrofit) {
// 返回类型必须为CompletableFuture.class
if (getRawType(returnType) != CompletableFuture.class) {
return null;
}
// 返回类型必须为泛型参数Type
if (!(returnType instanceof ParameterizedType)) {
throw new IllegalStateException("CompletableFuture return type must be parameterized"
+ " as CompletableFuture or CompletableFuture extends Foo>");
}
// 返回类型第一个参数Type
Type innerType = getParameterUpperBound(0, (ParameterizedType) returnType);
// 如果返回类型第一个参数Type不是Response,则返回BodyCallAdapter
if (getRawType(innerType) != Response.class) {
// Generic type is not Response. Use it for body-only adapter.
return new BodyCallAdapter<>(innerType);
}
// 如果返回类型第一个参数Type是Response,则必须也为泛型参数化Type
if (!(innerType instanceof ParameterizedType)) {
throw new IllegalStateException("Response must be parameterized"
+ " as Response or Response extends Foo>");
}
// 返回ResponseCallAdapter实例
Type responseType = getParameterUpperBound(0, (ParameterizedType) innerType);
return new ResponseCallAdapter<>(responseType);
}
BodyCallAdapter :将Call转为CompletableFuture
,是java8平台支持的特性private static final class BodyCallAdapter implements CallAdapter> {
private final Type responseType;
BodyCallAdapter(Type responseType) {
this.responseType = responseType;
}
@Override public Type responseType() {
return responseType;
}
@Override public CompletableFuture adapt(final Call call) {
final CompletableFuture future = new CompletableFuture() {
@Override public boolean cancel(boolean mayInterruptIfRunning) {
if (mayInterruptIfRunning) {
call.cancel();
}
return super.cancel(mayInterruptIfRunning);
}
};
call.enqueue(new Callback() {
@Override public void onResponse(Call call, Response response) {
if (response.isSuccessful()) {
future.complete(response.body());
} else {
future.completeExceptionally(new HttpException(response));
}
}
@Override public void onFailure(Call call, Throwable t) {
future.completeExceptionally(t);
}
});
return future;
}
}
ResponseCallAdapter:将原始Call转为CompletableFuture
private static final class ResponseCallAdapter
implements CallAdapter>> {
private final Type responseType;
ResponseCallAdapter(Type responseType) {
this.responseType = responseType;
}
@Override public Type responseType() {
return responseType;
}
@Override public CompletableFuture> adapt(final Call call) {
final CompletableFuture> future = new CompletableFuture>() {
@Override public boolean cancel(boolean mayInterruptIfRunning) {
if (mayInterruptIfRunning) {
call.cancel();
}
return super.cancel(mayInterruptIfRunning);
}
};
call.enqueue(new Callback() {
@Override public void onResponse(Call call, Response response) {
future.complete(response);
}
@Override public void onFailure(Call call, Throwable t) {
future.completeExceptionally(t);
}
});
return future;
}
}
适配第三方框架:RxJava2CallAdapterFactory的实现
public final class RxJava2CallAdapterFactory extends CallAdapter.Factory {
// 默认传的调度器是为空的
public static RxJava2CallAdapterFactory create() {
return new RxJava2CallAdapterFactory(null, false);
}
public static RxJava2CallAdapterFactory createAsync() {
return new RxJava2CallAdapterFactory(null, true);
}
public static RxJava2CallAdapterFactory createWithScheduler(Scheduler scheduler) {
if (scheduler == null) throw new NullPointerException("scheduler == null");
return new RxJava2CallAdapterFactory(scheduler, false);
}
// 调度器
private final @Nullable Scheduler scheduler;
// 是否异步
private final boolean isAsync;
// 构造器
private RxJava2CallAdapterFactory(@Nullable Scheduler scheduler, boolean isAsync) {
this.scheduler = scheduler;
this.isAsync = isAsync;
}
// 获取Call适配器
@Override
public CallAdapter, ?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
Class> rawType = getRawType(returnType);
// 如果返回类型为 Completable,则适配为Completable,为Completable相当于Runable,执行任务不会发射数据
if (rawType == Completable.class) {
return new RxJava2CallAdapter(Void.class, scheduler, isAsync, false, true, false, false,
false, true);
}
boolean isFlowable = rawType == Flowable.class;
boolean isSingle = rawType == Single.class;
boolean isMaybe = rawType == Maybe.class;
// 如果不是Observable、Flowable,Single,Maybe,则适配为null,因为RxJava2只有这几种被观察者
if (rawType != Observable.class && !isFlowable && !isSingle && !isMaybe) {
return null;
}
boolean isResult = false;
boolean isBody = false;
Type responseType;
if (!(returnType instanceof ParameterizedType)) {
String name = isFlowable ? "Flowable"
: isSingle ? "Single"
: isMaybe ? "Maybe" : "Observable";
throw new IllegalStateException(name + " return type must be parameterized"
+ " as " + name + " or " + name + " extends Foo>");
}
// 获取观察的数据类型
Type observableType = getParameterUpperBound(0, (ParameterizedType) returnType);
Class> rawObservableType = getRawType(observableType);
if (rawObservableType == Response.class) {
// 如果观察的数据类型为Response,则Response必须要有泛型参数,即observableType为ParameterizedType。然后不是result,也不是body.比如Observable>
if (!(observableType instanceof ParameterizedType)) {
throw new IllegalStateException("Response must be parameterized"
+ " as Response or Response extends Foo>");
}
// 获取Response的泛型参数Type
responseType = getParameterUpperBound(0, (ParameterizedType) observableType);
} else if (rawObservableType == Result.class) {
// Result和Response同理,是result,比如Observable>
if (!(observableType instanceof ParameterizedType)) {
throw new IllegalStateException("Result must be parameterized"
+ " as Result or Result extends Foo>");
}
responseType = getParameterUpperBound(0, (ParameterizedType) observableType);
isResult = true;
} else {
// 否则为body,即使用者自定义类型,比如Observable
responseType = observableType;
isBody = true;
}
// 然后传给RxJava2CallAdapter构造器,构造出对应条件的Call适配器
return new RxJava2CallAdapter(responseType, scheduler, isAsync, isResult, isBody, isFlowable,
isSingle, isMaybe, false);
}
}
RxJava2CallAdapter.java
// 负责把Call转为Rxjava的被观察者
final class RxJava2CallAdapter implements CallAdapter {
// 响应类型
private final Type responseType;
// 调度器
private final @Nullable Scheduler scheduler;
// 是否异步
private final boolean isAsync;
// 是否原始结果
private final boolean isResult;
// 是否是body结果
private final boolean isBody;
// 是否背压
private final boolean isFlowable;
// 是否Single
private final boolean isSingle;
// 是否Maybe
private final boolean isMaybe;
// 是否是Completable
private final boolean isCompletable;
RxJava2CallAdapter(Type responseType, @Nullable Scheduler scheduler, boolean isAsync,
boolean isResult, boolean isBody, boolean isFlowable, boolean isSingle, boolean isMaybe,
boolean isCompletable) {
this.responseType = responseType;
this.scheduler = scheduler;
this.isAsync = isAsync;
this.isResult = isResult;
this.isBody = isBody;
this.isFlowable = isFlowable;
this.isSingle = isSingle;
this.isMaybe = isMaybe;
this.isCompletable = isCompletable;
}
@Override public Type responseType() {
return responseType;
}
@Override public Object adapt(Call call) {
// 不管怎样,先转为Observable>
Observable> responseObservable = isAsync
? new CallEnqueueObservable<>(call)
: new CallExecuteObservable<>(call);
Observable> observable;
if (isResult) {
// 如果是Result类型,则转为ResultObservable
observable = new ResultObservable<>(responseObservable);
} else if (isBody) {
// 如果是用户自定义的Body类型,则转为BodyObservable
observable = new BodyObservable<>(responseObservable);
} else {
// 其它则返回Observable>
observable = responseObservable;
}
if (scheduler != null) {
observable = observable.subscribeOn(scheduler);
}
// 如果要支持背压,则把observable转为Flowable
if (isFlowable) {
return observable.toFlowable(BackpressureStrategy.LATEST);
}
// 如果要Single,则把observable转为Single
if (isSingle) {
return observable.singleOrError();
}
// 如果要Maybe,则把observable转为Maybe
if (isMaybe) {
return observable.singleElement();
}
// 如果要Completable,则把observable转为Completable
if (isCompletable) {
return observable.ignoreElements();
}
return observable;
}
}
2.2.5 callbackExecutor: Executor
回调执行器,即回调执行在哪个线程池提供的线程中:其实在Platform里面Android平台已经有一个MainThreadExecutor了,也可以自定义线程池,Retrofit在Androdi平台回调默认在主线程回调,所有没必要在切换线程
2.2.6 validateEagerly:boolean
是否提前验证Service接口方法,默认为false
3 Retrofit如何通过动态代理把一个接口转为具体的实现实例?
关键代码:
public T create(final Class service) {
Utils.validateServiceInterface(service);
if (validateEagerly) {
eagerlyValidateMethods(service);
}
return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class>[] { service },
new InvocationHandler() {
private final Platform platform = Platform.get();
@Override public Object invoke(Object proxy, Method method, @Nullable Object[] args)
throws Throwable {
// If the method is a method from Object then defer to normal invocation. 如果方法是object的,那么就执行object对应的方法
if (method.getDeclaringClass() == Object.class) {
return method.invoke(this, args);
}
// 如果平台支持默认方法实现,则调用默认方法实现,一般都不这样做,也许是适配最新的java接口支持默认实现
if (platform.isDefaultMethod(method)) {
return platform.invokeDefaultMethod(method, service, proxy, args);
}
// 大多数情况下都是先从Method中提取出ServiceMethod,然后通过ServiceMethod调用HttpCall来实现请求
return loadServiceMethod(method).invoke(args != null ? args : emptyArgs);
}
});
}
首先是拿到用户自定义的Service接口class,然后用java的Proxy.newProxyInstance
构造出一个动态代理,但是该代理并没有持有常规意义上已存在的被代理者的引用,而只是取得一个代理执行权,当然也可以理解成是代理HTTP Call。它首先从method中提取出HttpServiceMethod,HttpServiceMethod相当于是HttpCall调用方法的适配器,从而实现动态代理在被调用方法时,最终就是在调用HttpCall,这个就是Retrofit的精髓之处,Retrofit结合注解然后代理OkHttp,使使用者在做请求时以简洁的代码快速构造请求代码,比如你不必再写很多Request.Builder代码,不必再设计回调结果的转换代码等。