您的位置:首页 > 其它

Retrofit源码分析以及MVP框架封装使用

2016-06-23 17:29 399 查看
阅读此文前请先阅读Retrofit+okhttp网络框架介绍

从上文中我们已经了解通过如下代码即可得到返回给我们call 以及 response对象,今天我们通过源码来分析这个过程是如何实现的。

/**
* 获取天气数据
* @param cityname
* @param key
* @return
*/
@GET("/weather/index")
Call<WeatherData> getWeatherData(@Query("format") String format, @Query("cityname") String cityname, @Query("key") String key);


private static final String ENDPOINT = "http://v.juhe.cn";

private static final Retrofit sRetrofit = new Retrofit.Builder()
.baseUrl(ENDPOINT)
.addConverterFactory(GsonConverterFactory.create())
//.addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // 使用RxJava作为回调适配器
.build();
private static final ApiManagerService apiManager = sRetrofit.create(ApiManagerService.class);
ApiManager.getWeatherData(format,city).enqueue(new Callback<WeatherData>() {
@Override
public void onResponse(Call<WeatherData> call, Response<WeatherData> response) {
mWeatherOnListener.onSuccessData(response.body());
}

@Override
public void onFailure(Call<WeatherData> call, Throwable t) {
mWeatherOnListener.onFailure(t);
}
});


分析流程图



ok,那我们就开始按照以上流程图,来揭开Retrofit的面纱,下面逐步介绍,最后在简单总结。

源码分析

1、Retrofit的构建

这里是通过构造者模式进行构建retrofit对象,好在其内部的成员变量比较少,我们直接看build()方法。

public Builder() {
this(Platform.get());
}

public Retrofit build() {
if (baseUrl == null) {
throw new IllegalStateException("Base URL required.");
}

okhttp3.Call.Factory callFactory = this.callFactory;
if (callFactory == null) {
callFactory = new OkHttpClient();
}

Executor callbackExecutor = this.callbackExecutor;
if (callbackExecutor == null) {
callbackExecutor = platform.defaultCallbackExecutor();
}

// Make a defensive copy of the adapters and add the default Call adapter.
List<CallAdapter.Factory> adapterFactories = new ArrayList<>(this.adapterFactories);
adapterFactories.add(platform.defaultCallAdapterFactory(callbackExecutor));

// Make a defensive copy of the converters.
List<Converter.Factory> converterFactories = new ArrayList<>(this.converterFactories);

return new Retrofit(callFactory, baseUrl, converterFactories, adapterFactories,
callbackExecutor, validateEagerly);
}


baseUrl必须指定,这个是理所当然的;

然后可以看到如果不着急设置callFactory,则默认直接new

OkHttpClient(),可见如果你需要对okhttpclient进行详细的设置,需要构建OkHttpClient对象,然后传入;

接下来是callbackExecutor,这个想一想大概是用来将回调传递到UI线程了,当然这里设计的比较巧妙,利用platform对象,对平台进行判断,判断主要是利用Class.forName(“”)进行查找。

如果是Android平台,会自定义一个Executor对象,并且利用Looper.getMainLooper()实例化一个handler对象,在Executor内部通过handler.post(runnable)。

接下来是adapterFactories,这个对象主要用于对Call进行转化,基本上不需要我们自己去自定义。

最后是converterFactories,该对象用于转化数据,例如将返回的responseBody转化为对象等;当然不仅仅是针对返回的数据,还能用于一般备注解的参数的转化例如@Body标识的对象做一些操作,后面遇到源码详细再描述。

Class.forName(“”)查找的源码,值得学习,以后用来判断平台可以复制以下源码。

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) {
}
try {
Class.forName("org.robovm.apple.foundation.NSObject");
return new IOS();
} catch (ClassNotFoundException ignored) {
}
return new Platform();
}


2、外观模式(门面模式)

Retrofit给我们暴露的方法和类不多。核心类就是Retrofit,我们只管配置Retrofit,然后做请求。剩下的事情就跟上层无关了,只需要等待回调。这样大大降低了系统的耦合度。对于这种写法,我们叫外观模式(门面模式)。

几乎所有优秀的开源library都有一个门面。比如 Glide.with() ImageLoader.load() Alamofire.request() 。有个门面方便记忆,学习成本低,利于推广品牌。 Retrofit的门面就是 retrofit.create().

3、(重点)从retrofit.create()在往下分析

3.1retrofit如何为我们的接口实现实例

Retrofit+okhttp网络框架介绍

通过以上链接的学习,我们发现使用retrofit需要去定义一个接口,然后可以通过调用sRetrofit.create(ApiManagerService.class);方法,得到一个接口的实例,最后通过该实例执行我们的操作,那么retrofit如何实现我们指定接口的实例呢?

其实原理是:动态代理。但是不要被动态代理这几个词吓唬到,Java中已经提供了非常简单的API帮助我们来实现动态代理。

看源码前先看一个例子:

public interface ITest
{
@GET("/heiheihei")
public void add(int a, int b);

}
public static void main(String[] args)
{
ITest iTest = (ITest) Proxy.newProxyInstance(ITest.class.getClassLoader(), new Class<?>[]{ITest.class}, new InvocationHandler()
{
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
Integer a = (Integer) args[0];
Integer b = (Integer) args[1];
System.out.println("方法名:" + method.getName());
System.out.println("参数:" + a + " , " + b);

GET get = method.getAnnotation(GET.class);
System.out.println("注解:" + get.value());
return null;
}
});

iTest.add(3, 5);
}


输出结果为:

方法名:add
参数:3 , 5
注解:/heiheihei


可以看到我们通过Proxy.newProxyInstance产生的代理类,当调用接口的任何方法时,都会调用InvocationHandler#invoke方法,在这个方法中可以拿到传入的参数,注解等。

试想,retrofit也可以通过同样的方式,在invoke方法里面,拿到所有的参数,注解信息然后就可以去构造RequestBody,再去构建Request,得到Call对象封装后返回。

ok,下面看retrofit#create的源码:

(T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] { service },
new InvocationHandler() {
private final Platform platform = Platform.get();

@Override public Object invoke(Object proxy, Method method, Object... args)
throws Throwable {


哈,看这个,在看上面的例子,你应该明白retrofit为我们接口生成实例对象并不神奇,仅仅是使用了Proxy这个类的API而已,然后在invoke方法里面拿到足够的信息去构建最终返回的Call而已。

其实真正的动态代理一般是有具体的实现类的,只是在这个类调用某个方法的前后去执行一些别的操作,比如开事务,打log等等,这里暂不讨论。

3.2具体Call构建流程

我们构造完成retrofit,就可以利用retrofit.create方法去构建接口的实例了,上面我们已经分析了这个环节利用了动态代理,而且我们也分析了具体的Call的构建流程在invoke方法中,下面看代码:

public <T> T create(final Class<T> service) {
Utils.validateServiceInterface(service);
//...
return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] { service },
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object... args){
//...
ServiceMethod serviceMethod = loadServiceMethod(method);
OkHttpCall okHttpCall = new OkHttpCall<>(serviceMethod, args);
return serviceMethod.callAdapter.adapt(okHttpCall);
}
});
}


主要也就三行代码,第一行是根据我们的method将其包装成ServiceMethod,第二行是通过ServiceMethod和方法的参数构造retrofit2.OkHttpCall对象,第三行是通过serviceMethod.callAdapter.adapt()方法,将OkHttpCall进行代理包装;

下面一个一个的介绍:

ServiceMethod应该是最复杂的一个类了,包含了将一个method转化为Call的所有的信息。

#Retrofit class
ServiceMethod loadServiceMethod(Method method) {
ServiceMethod result;
synchronized (serviceMethodCache) {
result = serviceMethodCache.get(method);
if (result == null) {
result = new ServiceMethod.Builder(this, method).build();
serviceMethodCache.put(method, result);
}
}
return result;
}

#ServiceMethod
public ServiceMethod build() {
callAdapter = createCallAdapter();
responseType = callAdapter.responseType();
if (responseType == Response.class || responseType == okhttp3.Response.class) {
throw methodError("'"
+ Utils.getRawType(responseType).getName()
+ "' is not a valid response body type. Did you mean ResponseBody?");
}
responseConverter = createResponseConverter();

for (Annotation annotation : methodAnnotations) {
parseMethodAnnotation(annotation);
}

int parameterCount = parameterAnnotationsArray.length;
parameterHandlers = new ParameterHandler<?>[parameterCount];
for (int p = 0; p < parameterCount; p++) {
Type parameterType = parameterTypes[p];
if (Utils.hasUnresolvableType(parameterType)) {
throw parameterError(p, "Parameter type must not include a type variable or wildcard: %s",
parameterType);
}

Annotation[] parameterAnnotations = parameterAnnotationsArray[p];
if (parameterAnnotations == null) {
throw parameterError(p, "No Retrofit annotation found.");
}

parameterHandlers[p] = parseParameter(p, parameterType, parameterAnnotations);
}

return new ServiceMethod<>(this);
}


直接看build方法,首先拿到这个callAdapter最终拿到的是我们在构建retrofit里面时adapterFactories时添加的,即为:new

ExecutorCallbackCall<>(callbackExecutor,

call),该ExecutorCallbackCall唯一做的事情就是将原本call的回调转发至UI线程。

接下来通过callAdapter.responseType()返回的是我们方法的实际类型,例如:
Call<WeatherData>,
则返回WeatherData类型,然后对该类型进行判断。

接下来是createResponseConverter拿到responseConverter对象,其当然也是根据我们构建retrofit时,addConverterFactory添加的ConverterFactory对象来寻找一个合适的返回,寻找的依据主要看该converter能否处理你编写方法的返回值类型,默认实现为BuiltInConverters,仅仅支持返回值的实际类型为ResponseBody和Void,也就说明了默认情况下,是不支持
Call<WeatherData>
这类类型的。

接下来就是对注解进行解析了,主要是对方法上的注解进行解析,那么可以拿到httpMethod以及初步的url(包含占位符)。

后面是对方法中参数中的注解进行解析,这一步会拿到很多的ParameterHandler对象,该对象在toRequest()构造Request的时候调用其apply方法。

ok,这里我们并没有去一行一行查看代码,其实意义也不太大,只要知道ServiceMethod主要用于将我们接口中的方法转化为一个Request对象,于是根据我们的接口返回值确定了responseConverter,解析我们方法上的注解拿到初步的url,解析我们参数上的注解拿到构建RequestBody所需的各种信息,最终调用toRequest的方法完成Request的构建。

接下来看OkHttpCall的构建,构造函数仅仅是简单的赋值

OkHttpCall(ServiceMethod<T> serviceMethod, Object[] args) {
this.serviceMethod = serviceMethod;
this.args = args;
}


最后一步是serviceMethod.callAdapter.adapt(okHttpCall)

我们已经确定这个callAdapter是ExecutorCallAdapterFactory.get()对应代码为:

final class ExecutorCallAdapterFactory extends CallAdapter.Factory {
final Executor callbackExecutor;

ExecutorCallAdapterFactory(Executor callbackExecutor) {
this.callbackExecutor = callbackExecutor;
}

@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<?>>() {
@Override public Type responseType() {
return responseType;
}

@Override public <R> Call<R> adapt(Call<R> call) {
return new ExecutorCallbackCall<>(callbackExecutor, call);
}
};
}


可以看到adapt返回的是ExecutorCallbackCall对象,继续往下看:

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;
}

@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.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.execute(new Runnable() {
@Override public void run() {
callback.onFailure(ExecutorCallbackCall.this, t);
}
});
}
});
}
@Override public Response<T> execute() throws IOException {
return delegate.execute();
}
}


你可以将 ExecutorCallbackCall 当作是ProxyCall,而真正去执行请求的DelegateCall是 OkHttpCall 。之所以要有个proxy类,是希望在delegate操作的前后去做一些操作。这里的操作就是线程转换,将子线程切换到主线程上去。

简单的解释下,enqueue()方法是异步的,也就是说,当你调用 OkHttpCall 的enqueue方法,回调的callback是在子线程中的,如果你希望在主线程接受回调,那需要通过Handler转换到主线程上去。 ExecutorCallbackCall 就是用来干这个事。当然以上是原生retrofit使用的切换线程方式。如果你用rxjava,那就不会用到这个 ExecutorCallbackCall 而是 RxJava 的Call了。这里不展开。

3.3执行Call

我们已经拿到了经过封装的ExecutorCallbackCall类型的call对象,实际上就是我们实际在写代码时拿到的call对象,那么我们一般会执行enqueue方法,看看源码是怎么做的

首先是ExecutorCallbackCall.enqueue方法,代码在3.2,可以看到除了将onResponse和onFailure回调到UI线程,主要的操作还是delegate完成的,这个delegate实际上就是OkHttpCall对象,也就是设计模式中的静态代理,那么我们看它的enqueue方法。

@Override
public void enqueue(final Callback<T> callback)
{
okhttp3.Call call;
Throwable failure;

synchronized (this)
{
if (executed) throw new IllegalStateException("Already executed.");
executed = true;

try
{
call = rawCall = createRawCall();
} catch (Throwable t)
{
failure = creationFailure = t;
}
}

if (failure != null)
{
callback.onFailure(this, failure);
return;
}

if (canceled)
{
call.cancel();
}

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();
}
}
});
}


没有任何神奇的地方,内部实际上就是okhttp的Call对象,也是调用okhttp3.Call.enqueue方法。

中间对于okhttp3.Call的创建代码为:

private okhttp3.Call createRawCall() throws IOException
{
Request request = serviceMethod.toRequest(args);
okhttp3.Call call = serviceMethod.callFactory.newCall(request);
if (call == null)
{
throw new NullPointerException("Call.Factory returned null.");
}
return call;
}


可以看到,通过serviceMethod.toRequest完成对request的构建,通过request去构造call对象,然后返回.

与上文一开始首尾相接。

到这里,我们整个源码的流程分析就差不多了,目的就掌握一个大体的原理和执行流程,了解下几个核心的类。

那么总结一下:

首先构造retrofit,几个核心的参数呢,主要就是baseurl,callFactory(默认okhttpclient),converterFactories,adapterFactories,excallbackExecutor。

然后通过create方法拿到接口的实现类,这里利用Java的Proxy类完成动态代理的相关代理

在invoke方法内部,拿到我们所声明的注解以及实参等,构造ServiceMethod,ServiceMethod中解析了大量的信息,最痛可以通过toRequest构造出okhttp3.Request对象。有了okhttp3.Request对象就可以很自然的构建出okhttp3.call,最后calladapter对Call进行装饰返回。

拿到Call就可以执行enqueue或者execute方法了

ok,了解这么多足矣。看到这里可能有些疲惫了,放松一下,在进行下面的实用吧。

使用实例

1、MVP的工作原理



以上是MVP的工作原理图。其中大家注意的Presenter操作View和Mode都是通过接口来实现直接的调用。

MVP的工作流程

Presenter负责逻辑的处理;

Model提供数据;

View负责显示;

作为一种新的模式,在MVP中View并不直接使用Model,它们之间的通信是通过Presenter来进行的,所有的交互都发生在Presenter内部,而在MVC中View会从直接Model中读取数据而不是通过 Controller。

2、MVP框架封装结构图



api包主要存放网络请求接口

bean包中存放实体类

model包中存放处理数据

pesenter包中存放主导器

view包中存放界面处理

这里由于是介绍Retrofit,所以目前只贴出api层,model层的代码,其余层的代码后面会给出下载地址,这里简单介绍一下这样写的好处。

我们可以把Presenter当做是一个桥梁,Model和View要通信必须经过Presenter,这样的话,Model层与View层就可以完全隔离,好处在于,以后项目中,如果要替换其他的网络框架,我们只需更换API层的接口,以及Model层回调的代码,其他的层的代码都不需要再动,这样各层之间保持单一职责。代码的易读性变得更强了,如果有新人要了解Retorfit,也只用了解API层。如果一定要说缺点的话,可能一次编程的时候多写一些代码

下面给出Demo中请求的网络地址

聚合函数API

Demo中请求的两个API:

http://v.juhe.cn/weather/index?format=2&cityname=%E8%8B%8F%E5%B7%9E&key=您申请的KEY(获取天气数据)

http://v.juhe.cn/weather/uni?dtype=&key=8ce7c2ac685f5e0f9743d305a68aaf5a(获取天气种类和标识列表)

API层代码:

ApiManager

public class ApiManager {
/**
* 基础地址
*/
private static final String ENDPOINT = "http://v.juhe.cn";

private static final Retrofit sRetrofit = new Retrofit.Builder()
.baseUrl(ENDPOINT)
.addConverterFactory(GsonConverterFactory.create())
//.addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // 使用RxJava作为回调适配器
.build();
private static final ApiManagerService apiManager = sRetrofit.create(ApiManagerService.class);

/**
* 获取天气数据
* @param city
* @return
*/
public static Call<WeatherData> getWeatherData(String format, String city) {
Call<WeatherData> call = apiManager.getWeatherData(format, city, "8ce7c2ac685f5e0f9743d305a68aaf5a");
return  call;
}

/**
* 获取天气种类
* @param type
* @return
*/
public static Call<WeatherType> getWeatherType(int type) {
Call<WeatherType> call = apiManager.getWeatherType(type+"", "8ce7c2ac685f5e0f9743d305a68aaf5a");
return  call;
}

}


ApiManagerService

public interface ApiManagerService {
/**
* 获取天气数据
* @param cityname
* @param key
*/
@GET("/weather/index")
Call<WeatherData> getWeatherData(@Query("format") String format, @Query("cityname") String cityname, @Query("key") String key);

/**
* 获取天气种类和标识列表
* @param dtype
* @param key
* @return  http://v.juhe.cn/weather/uni?dtype=&key=8ce7c2ac685f5e0f9743d305a68aaf5a */

@GET("/weather/uni")
Call<WeatherType> getWeatherType (@Query("dtype") String dtype, @Query("key") String key);

}


MODEL层代码

WeatherModelImp

public class WeatherModelImp  implements WeatherModel {

private WeatherOnListener mWeatherOnListener;

public WeatherModelImp(WeatherOnListener mWeatherOnListener) {
this.mWeatherOnListener = mWeatherOnListener;
}

@Override
public void getWeatherData(String format,String city) {
ApiManager.getWeatherData(format,city).enqueue(new Callback<WeatherData>() {
@Override
public void onResponse(Call<WeatherData> call, Response<WeatherData> response) {
mWeatherOnListener.onSuccessData(response.body());
}

@Override
public void onFailure(Call<WeatherData> call, Throwable t) {
mWeatherOnListener.onFailure(t);
}
});
}

@Override
public void getWeatherType(int type) {
ApiManager.getWeatherType(type).enqueue(new Callback<WeatherType>() {
@Override
public void onResponse(Call<WeatherType> call, Response<WeatherType> response) {
Log.i("WeatherData","response.body()="+response.body());
mWeatherOnListener.onSuccessType(response.body());
}

@Override
public void onFailure(Call<WeatherType> call, Throwable t) {
mWeatherOnListener.onFailure(t);
}
});
}

//以下为RXJava回调方式。
/* ApiManager.getWeatherData(format, city).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<WeatherData>() {
@Override
public void call(WeatherData weatherData) {
mWeatherOnListener.onSuccess(weatherData);
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
mWeatherOnListener.onFailure(throwable);
}
});*/

public interface WeatherOnListener{
void onSuccessData(WeatherData s);
void onFailure(Throwable e);
void onSuccessType(WeatherType body);
}
}


代码运行结果



代码下载地址

Retrofit网络框架+MVP框架源码案例

欢迎大家Star,如有问题,直接回复。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: