Retrofit2+RxJava+LoganSquare最佳實(shí)踐
基本介紹
Retrofit是Square的一個(gè)非常知名的開(kāi)源的網(wǎng)絡(luò)請(qǐng)求庫(kù)抖所,并且是由Android大神JakeWharton親自操刀撤缴。
現(xiàn)在Retrofit已經(jīng)出到2.0.2版本了质帅,與前的1.9版本相差很大绣夺,并且官方強(qiáng)烈推薦2.0版本栅螟,所以在此就只聊2.0以后的版本具滴。
馬上開(kāi)擼米奸!
首先肯定要在build.gradle中添加retrofit的依賴(lài)。
compile 'com.squareup.retrofit2:retrofit:2.0.2'
創(chuàng)建一個(gè)HTTP API的接口灌旧。
public interface ZhihuService {
@GET("news/latest")
Call<Daily> getLatest();
}
實(shí)例化ZhihuService绑咱,然后發(fā)起HTTP請(qǐng)求。
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://news-at.zhihu.com/api/4/")
.build();
ZhihuService service = retrofit.create(ZhihuService.class);
Call<Daily> daily = service.getLatest();
說(shuō)好的RxJava呢枢泰?
RxJava到底是什么描融?
Reactive Extensions for the JVM – a library for composing asynchronous and event-based programs using observable sequences for the Java VM.
如果不熟悉RxJava的朋友,可以看看這篇文章衡蚂,給 Android 開(kāi)發(fā)者的 RxJava 詳解
Retrofit2.0依然是支持RxJava的窿克,但和以前的集成在一起不同,現(xiàn)在是完全獨(dú)立的毛甲,需要自己添加CallAdapter年叮。這樣的好處是更靈活,更解耦玻募。
/**
* Add a call adapter factory for supporting service method return types other than {@link
* Call}.
*/
public Builder addCallAdapterFactory(CallAdapter.Factory factory) {
adapterFactories.add(checkNotNull(factory, "factory == null"));
return this;
}
添加RxJavaCallAdapter
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(HOST_NAME)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
現(xiàn)在Retrofit可以使用RxJava了
首先修改我們的API接口只损。
public interface ZhihuService {
@GET("news/latest")
Observable<Daily> getLatest();
}
RxJava的使用在這里!七咧!
ZhihuService service = retrofit.create(ZhihuService.class);
Observable<Daily> observable = service.getLatest();
observable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Daily>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Daily daily) {
}
});
Retrofit Converter的使用
Converter和CallAdapter一樣跃惫,也從Retrofit中分離出來(lái),需要自己添加艾栋。官方提供了很多convertes.
- gson
- jackson
- moshi
- protobuf
- scalars
- simplexml
- wire
但是發(fā)現(xiàn)沒(méi)有LoganSqaure爆存,那只有自己擼了,還好在github上已經(jīng)有寫(xiě)好的裹粤,是時(shí)候發(fā)揮我們的拿來(lái)主義的精神了终蒂,不然怎么說(shuō)我們都是github的搬運(yùn)工呢。
complie 'com.github.aurae.retrofit2:converter-logansquare:1.4.0'
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(HOST_NAME)
.addConverterFactory(LoganSquareConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
為什么使用LoganSquare來(lái)解析JSON遥诉?
天下武功唯快不破拇泣!因?yàn)長(zhǎng)oganSquare快啊矮锈!
Note: Our "400% or more" performance improvement metric was determined using ART. While LoganSquare still comes out on top with Dalvik, it seems as though the comparison is much closer. The benchmarks shown are actual screenshots taken from a 2nd gen Moto X.
添加LoganSquare
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
}
}
apply plugin: 'com.neenbedankt.android-apt'
dependencies {
apt 'com.bluelinelabs:logansquare-compiler:1.3.6'
compile 'com.bluelinelabs:logansquare:1.3.6'
}
打印Log
很多時(shí)候霉翔,我們希望打印Http請(qǐng)求的Log,這樣方便調(diào)試苞笨。在老版本的Retrofit中债朵,有個(gè)方法
new RestAdapter.Builder()
.setLogLevel(RestAdapter.LogLevel.FULL);
但是子眶,在Retrofit2.0后,不再提供該方法了序芦,需要依賴(lài)okhttp中的HttpLoggingInterceptor臭杰。
compile 'com.squareup.okhttp3:logging-interceptor:3.0.1'
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(HOST_NAME)
.client(okHttpClient)
.addConverterFactory(LoganSquareConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
看了這么多,源碼呢谚中?
源碼當(dāng)然要獻(xiàn)上的渴杆,之前的一個(gè)開(kāi)源的APP叫IDaily,其中的HTTP請(qǐng)求就是采用的Retrofit2+RxJava+LoganSquare宪塔,敢興趣的朋友磁奖,可以看一下。
That's all!
到此就結(jié)束了, 初次寫(xiě)類(lèi)似的文章某筐,如有錯(cuò)誤比搭,望見(jiàn)諒!謝謝南誊!