Retrofit結(jié)合Rxjava封裝思路:
- 主要分為四個(gè)部分:實(shí)體類(lèi) 辛慰,Observable ,Subscriber燕垃,Retrofit裹纳。
實(shí)體類(lèi)
一般客戶端都是通過(guò)鏈接從服務(wù)端獲取數(shù)據(jù),然后再注入到應(yīng)用中棚潦,從而更新UI。返回的數(shù)據(jù)一般為JSON。
{
items: [],
has_more: true,
quota_max: 300,
quota_remaining: 299
}
常見(jiàn)結(jié)構(gòu)就是如此身弊,對(duì)于我們個(gè)人而言呢有用的僅僅是tems部分,而且后期需求變化的話列敲,items里的json數(shù)據(jù)結(jié)構(gòu)會(huì)發(fā)生改變的阱佛,對(duì)應(yīng)的類(lèi)結(jié)構(gòu)會(huì)發(fā)生改變,所以用泛型來(lái)解決items類(lèi)多變的問(wèn)題戴而。把items中用到的類(lèi)單獨(dú)封裝凑术。
public class StackUserEntity<T> {
/**
* items : [{"reputation":904115,"creation_date":1222430705,"user_type":"registered","user_id":22656,"accept_rate":86,"location":"Reading, United Kingdom","website_url":"http://csharpindepth.com","link":"http://stackoverflow.com/users/22656/jon-skeet","profile_image":"https://www.gravatar.com/avatar/6d8ebb117e8d83d74ea95fbdd0f87e13?s=128&d=identicon&r=PG","display_name":"Jon Skeet"}]
* has_more : true
* quota_max : 300
* quota_remaining : 299
*/
private boolean has_more;
private int quota_max;
private int quota_remaining;
private T items;
}
Observable<StackUserEntity<List<ItemsBean>>>
Retrofit
此類(lèi)更多封裝的時(shí)關(guān)于Retrofit的配置及請(qǐng)求過(guò)程,并不涉及服務(wù)接口所意。以單例模式封裝淮逊。
public class HttpMethodes{
public static final String baseUrl = "https://api.douban.com/v2/movie/";
private static final int DEFAULT_TIMEOUT = 5;
private Retrofit retrofit;
private static HttpMethodes httpMethodes;
//構(gòu)造函數(shù)私有化
private HttpMethodes() {
OkHttpClient.Builder builder =new OkHttpClient.Builder();
builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.client(builder.build())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
//懶漢式單例,并加入線程鎖扶踊,使得線程安全(不會(huì)因?yàn)槎嗑€程調(diào)用時(shí)創(chuàng)造出兩個(gè)實(shí)例)
public static HttpMethodes getInstance() {
if (httpMethodes == null) {
synchronized (HttpMethodes.class) {
if (httpMethodes == null) {
httpMethodes = new HttpMethodes();
}
}
}
return httpMethodes;
}
//這里是把線程的調(diào)度封裝了泄鹏,避免重復(fù)寫(xiě)。
public <T> void getMovie(Subscriber<T> subscriber,Observable<T> observable) {
toSubscriber(observable,subscriber);
}
//因?yàn)槭菃卫鎏矗?wù)接口的對(duì)象創(chuàng)建和url的參數(shù)是不能寫(xiě)死的命满。這里也用泛型。
public <T> T toService(final Class<T> from) {
return retrofit.create(from);
}
private void toSubscriber(Observable o , Subscriber s) {
o.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(s);
}
}
Observable
Observable這部分更多的是封裝Retrofit的服務(wù)接口參數(shù)傳遞即事件的處理绣版。因這部分為變化的不可能在Retrofit單例那里封裝胶台。
private Observable<List<ItemsBean>> getSource() {
return methodes.toService(StackExchangeService.class)
.getSource(10) //此處使用map操作符呢是為了提取StackUserEntity實(shí)體類(lèi)部分的List<ItemsBean>;
.map(new Func1<StackUserEntity<List<ItemsBean>>, List<ItemsBean>>() {
@Override
public List<ItemsBean> call(StackUserEntity<List<ItemsBean>> listStackUserEntity) {
return listStackUserEntity.getItems();
}
});
}
Subscriber
創(chuàng)建一個(gè)繼承Subscriber的抽象類(lèi)杂抽,把OnNext( )定義為抽象方法诈唬,因?yàn)镺nNext()方法中,更多的傳遞數(shù)據(jù)給UI使用缩麸。
public abstract class ProgressSubscriber<T> extends Subscriber<T> {
private SubscriberOnNextListener mSubscriber;
@Inject
public Context context;
private ProgressDialog dialog;
public void setmSubscriber(SubscriberOnNextListener mSubscriber) {
this.mSubscriber = mSubscriber;
}
public void setContext(Context context) {
this.context = context;
}
@Override
public void onStart() {
showProgressDialog();
super.onStart();
}
@Override
public void onCompleted() {
destroyProgress();
Toast.makeText(context, "當(dāng)前任務(wù)已經(jīng)完成", Toast.LENGTH_SHORT).show();
}
@Override
public void onError(Throwable e) {
destroyProgress();
Toast.makeText(context, "當(dāng)前任務(wù)出現(xiàn)了錯(cuò)誤铸磅,請(qǐng)稍候重試", Toast.LENGTH_SHORT).show();
}
//可以根據(jù)需求寫(xiě)入正確的類(lèi)型
@Override
abstract public void onNext(T t);
private void destroyProgress() {
if (dialog!=null) {
dialog.dismiss();
}
dialog = null;
}
private void showProgressDialog() {
if (dialog == null) {
dialog = new ProgressDialog(context);
dialog.setCancelable(true);
dialog.setMessage("正在加載中,請(qǐng)稍候杭朱!");
dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
if (! isUnsubscribed()) {
unsubscribe(); //當(dāng)加載框阅仔,加載完成時(shí)取消對(duì)Observable的訂閱(即關(guān)閉url連接。)
}
}
});
}
if (! dialog.isShowing()) {
dialog.show();
}
}
}