您的位置:首页 > 理论基础 > 计算机网络

RxJava+Retrofit+OkHttp实战

2017-07-03 16:53 344 查看
概述

一直想写一篇关于RxJava+Retrofit+OkHttp的结合使用的博客,今天终于有时间整理一下了,希望能给大家一点点帮助就好。

这是本项目的github链接Rxjava+Retrofit+OkHttp实战

给大家推荐两个学习的链接

给 Android 开发者的 RxJava 详解

RxJava
与 Retrofit 结合的最佳实践

1 首先需要导入依赖库

compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.google.code.gson:gson:2.6.2'
compile 'io.reactivex:rxjava:1.1.0'
compile 'io.reactivex:rxandroid:1.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'


2、写一个类Retrofit.java,里面主要是将RXJava和Retrofit和okhttp结合

public RetrofitClient(Context context) {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.connectTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS);
builder.writeTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS);
builder.readTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS);

HttpCommonInterceptor commonInterceptor = new HttpCommonInterceptor.Builder()
.addHeaderParams("paltform", "android")
.addHeaderParams("userToken", "1234343434dfdfd3434")
.addHeaderParams("userId", "123445")
.build();
builder.addInterceptor(commonInterceptor);

mRetrofit = new Retrofit.Builder()
.client(builder.build())
//添加返回值为observable<T>的支持 添加之后ArtistService中返回值就变成了Observable
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
//增加返回值为Gson的支持
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(getBaseUrl())
.build();
}

protected abstract String getBaseUrl();

public void unsubscribe(String tag) {
if (mSubscriptionsMap.containsKey(tag)) {
CompositeSubscription subscriptions = mSubscriptionsMap.get(tag);
subscriptions.unsubscribe();
mSubscriptionsMap.remove(tag);
}
}

protected void addSubscription(String tag, Subscription subscription) {
if (TextUtils.isEmpty(tag)) {
return;
}
CompositeSubscription subscriptions;
if (mSubscriptionsMap.containsKey(tag)) {
subscriptions = mSubscriptionsMap.get(tag);
} else {
subscriptions = new CompositeSubscription();
}
subscriptions.add(subscription);
mSubscriptionsMap.put(tag, subscriptions);
}
3、写一个接口,使用RxJava的Observable定义一个泛型的参数(便于在后期维护迭代,需要和后台约定一个返回类型,比如String Code,T data)

public interface ArtistService {
//    https://api.douban.com/v2/movie/top250?start=0&count=10 @GET("top250")
Observable<ArtistResult<List<Movie>>> getTop250(@Query("start") int start, @Query("count") int count);
}
4、上面的RetrofitClient类是一个抽象类,我们需要类继承它并且实现其中的方法,这个类中可以写很多调用的方法

public class ArtistClient extends RetrofitClient {

private ArtistService mMovieService;

public ArtistClient(Context context) {
super(context);
mMovieService = mRetrofit.create(ArtistService.class);
}

@Override
protected String getBaseUrl() {
return Constant.BASE_URL;
}

private static class SingletonHolder {
public static final ArtistClient INSTANCE = new ArtistClient(App.get());
}

public static ArtistClient getInstance() {
return SingletonHolder.INSTANCE;
}

public void getTop250(String tag, Subscriber<List<Movie>> subscriber,int start,int count){
Subscription subscription = mMovieService.getTop250(start,count)
.map(new ArtistResultTransformer<List<Movie>>())
.compose(ArtistUtils.<List<Movie>>applySchedulers())
.subscribe(subscriber);
addSubscription(tag,subscription);
}

}


5 最后在Activity中调用此方法

@Override
protected void initView() {
mMZBannerView = (MZBannerView) findViewById(R.id.my_banner);
mArtistClient = new ArtistClient(this);
getMoviesList();
}

private void getMoviesList() {
ArtistClient.getInstance().getTop250(TAG, new ArtistSubscriber<>(this, onGetTop250Listener, true, "加载中..."), 0, 10);
}

public OnNextListener<List<Movie>> onGetTop250Listener = new OnNextListener<List<Movie>>() {
@Override
public void onNext(List<Movie> movies) {
mMZBannerView.setPages(movies, new MZHolderCreator<BannerViewHolder>() {
@Override
public BannerViewHolder createViewHolder() {
return new BannerViewHolder();
}
});
mMZBannerView.start();
}
};


这里呢,我封装了几个类,第一个是ArtistSubscriber.java,它是继承自Subscriber的,里面呢实现了onStart(),onCompleted(),onNext(T t),onError(Throwable e)

其中在onNext方法中我们定义了一个监听在Activity中进行操作,上面有代码参考

还有一些就是一些简单的类了,比如返回值的泛型ArtistResult<T>类,加载出数据前的一个LoadingDialog类等

上面附有此项目的GitHub链接




内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息