RxJava在Android开发中以及非常的普遍了,网上对应的资料也非常的多,这里就不多做介绍了,这里主要写一下RxJava的线程转换
用RxJava结合Retrofit网络请求接口一般的写法如下
RetrofitManager.create(ApiService.class)
.login(username, password)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<DataResponse<User>>() {
@Override
public void accept(DataResponse<User> response) throws Exception {
if (response.getErrorCode() == 0) {
mView.loginSuccess(response.getData());
} else {
mView.showFaild(String.valueOf(response.getErrorMsg()));
}
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
mView.showFaild(throwable.getMessage());
}
});
其中subscribeOn(Schedulers.io())
和observeOn(AndroidSchedulers.mainThread())
可以清楚的看到线程之间的切换(具体的函数用法请移步RxJava2大全)
但是一般在实际开发中,我们所用到的接口和耗时操作处理是非常多的,每次都要写上这么两行也是非常烦人,所以需要用新的方式用一行代码去实现线程切换
代码如下:
/**
* 通用的Rx线程转换类
* 参考:http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0819/3327.html
*/
public class RxSchedulers {
static final ObservableTransformer schedulersTransformer = new ObservableTransformer() {
@Override
public ObservableSource apply(Observable upstream) {
return (upstream).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
};
public static <T> ObservableTransformer<T, T> applySchedulers() {
return (ObservableTransformer<T, T>) schedulersTransformer;
}
}
有了这个工具类之后,在请求网络接口的时候就可以这么写了
RetrofitManager.create(ApiService.class)
.login(username, password)
.compose(RxSchedulers.<DataResponse<User>>applySchedulers())
.subscribe(new Consumer<DataResponse<User>>() {
@Override
public void accept(DataResponse<User> response) throws Exception {
if (response.getErrorCode() == 0) {
mView.loginSuccess(response.getData());
} else {
mView.showFaild(String.valueOf(response.getErrorMsg()));
}
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
mView.showFaild(throwable.getMessage());
}
});
是不是清晰明了了许多呢
网友评论