移步Retrofit--网络通讯框架
Platform的工作
- 根据不同平台初始化不同平台的对应继承子类,此处就是Android类
- Android类可以返回一个回调回UI线程的执行器
- Android类可以返回网络请求适配器工厂ExecutorCallAdapterFactory
源码分析
1. 通过Retrofit内的调用进入Platform
public Builder() {
this(Platform.get());
}
class Platform {
private static final Platform PLATFORM = findPlatform();
static Platform get() {
return PLATFORM;
}
...
}
通过上面代码可以看出将要进入findPlatform()
方法
private static Platform findPlatform() {
try {
//为Android平台,所以会生成Android类
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类
2. Android类
static class Android extends Platform {
@Override public Executor defaultCallbackExecutor() {
return new MainThreadExecutor();
}
@Override CallAdapter.Factory defaultCallAdapterFactory(@Nullable Executor callbackExecutor) {
if (callbackExecutor == null) throw new AssertionError();
return new ExecutorCallAdapterFactory(callbackExecutor);
}
static class MainThreadExecutor implements Executor {
private final Handler handler = new Handler(Looper.getMainLooper());
@Override public void execute(Runnable r) {
handler.post(r);
}
}
}
这里面有两个方法,
- 生成一个回调回UI线程的执行器
MainThreadExecutor
- 生成一个网络请求适配器工厂ExecutorCallAdapterFactory
- MainThreadExecutor执行器里面持有Ui线程的Handler,可以将执行结果返回至Ui线程内