之前的一篇文章Retrofit初识尝试用了下 Retrofit。说来惭愧,到现在才写这篇文章。由于项目中没有使用的缘故,一直停留在了解的程度。最近自己学习做了个Gank客户端,一点点学习当前主流的技术,今天研究了下 Retrofit 的源码,颇有感触,便记录下来。
使用
关于正常的使用,参考之前的那篇文章。这里再写一下结合 RxJava 的使用。
- 定义接口:
1
2
3
4
5
6
7
8public interface GankService {
@GET("day/{year}/{month}/{day}")
Observable<GankDailyResult> getDailyData(@Path("year") int year, @Path("month") int month, @Path("day") int day);
@GET("data/{type}/{count}/{page}")
Observable<GankCategoryResult> getCategoryData(@Path("type") String type, @Path("count") int count, @Path("page") int page);
} - 初始化 Retrofit,生成代理对象:
1
2
3
4
5
6
7
8Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_GANK_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(okHttpClient.build())
.build();
mService = retrofit.create(GankService.class); - 调用接口:
1
2
3
4
5
6
7
8
9
10
11
12GankRequestManager.getInstance().getCategory(type, PAGE_SIZE, mPage)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<GankCategoryResult>() {
@Override
public void accept(GankCategoryResult gankCategoryResult) throws Exception {
mPage++;
if (mView != null) {
mView.showList(type, gankCategoryResult.results);
}
}
});