Retrofit + Rxjava + RxAndroid實現網路請求
之前自己實現了一個新聞類閱讀APP,最近想使用當下流行的Retrofit + Rxjava + RxAndroid + MVP架構來重構一下,本文以每日一文作為資料來源API做一個簡單的示例,來介紹一下如何使用Retrofit + Rxjava + RxAndroid來實現網路資料請求與解析。
一、配置
在你專案的build.gradle檔案中加入如下配置:
//rxjava
compile 'io.reactivex:rxandroid:1.2.0'
compile 'io.reactivex:rxjava:1.1.5'
//retrofit
compile 'com.google.code.gson:gson:2.7'
compile 'com.squareup.retrofit2:retrofit:2.2.0'
compile 'com.squareup.retrofit2:converter-gson:2.2.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'
compile 'com.squareup.okhttp:okhttp:2.4.0'
二、生成資料實體
把API返回的Json資料通過Android Studio的GsonFormat外掛進行轉換生成資料實體類DailyReadEntity(自動構建的程式碼,很長就不往上貼了)
public interface DailyReadService {
@GET("article/today?dev=1")
Observable<DailyReadEntity> getTodayDailyRead();
@GET("article/day?dev=1&date=")
Observable<DailyReadEntity> getParticularDayDailyRead(@Query("date") int date );
}
四、構建retrofit例項並建立請求service
Retrofit retrofit = new Retrofit.Builder ()
.baseUrl("https://interface.meiriyiwen.com/") //主機URL
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
DailyReadService dailyReadService = retrofit.create(DailyReadService.class);
五、呼叫請求service中定義的方法請求資料
dailyReadService.getTodayDailyRead()
.subscribeOn(Schedulers.io()) //在新執行緒裡面處理網路請求
.observeOn(AndroidSchedulers.mainThread()) //在主執行緒裡面接受返回的資料
.subscribe(new Subscriber<DailyReadEntity>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(DailyReadEntity today) {
Log.d(TAG,"onNext daily = " + today.toString());
}
});
dailyReadService.getParticularDayDailyRead(20170511)
.subscribeOn(Schedulers.io()) //在新執行緒裡面處理網路請求
.observeOn(AndroidSchedulers.mainThread()) //在主執行緒裡面接受返回的資料
.subscribe(new Subscriber<DailyReadEntity>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(DailyReadEntity particularDay) {
Log.d(TAG,"onNext particularDay = " + particularDay.toString());
}
});
小結:
我自己在實踐過程中所遇到的問題是在實現請求服務介面的時候@Path和@Query等介面的使用,查看了一下Retrofit的官方文件和具體介面的註釋很快就解決了。另外,這是一個與網路相關的功能,是一個耗時任務需要在子執行緒中執行。這個時候就看出來這套框架的優點了,你只需呼叫subscribeOn在新執行緒中請求,然後呼叫observeOn在主執行緒中接受資料,兩行程式碼就解決了,再也不用自己去建立新的執行緒然後再通過handler通知主執行緒來重新整理資料了。
最後要吐槽一下,昨天在用網易新聞的一個頻道實現邏輯做測試的時候始終丟擲retrofit2.adapter.rxjava.HttpException: HTTP 403 Forbidden異常,印象裡就成功了一把。檢查了很多遍也做了很多嘗試都不行,耗了一個下午,log中也無其他異常,最後換了一個其他頻道,終於可以正常解析了,原來是伺服器異常導致的。這個故事告訴我們,有的時候你需要換個角度思考問題。