public class RxAsyncHelper<T> {
Observable<T> observable;
public RxAsyncHelper(final T t){
observable = Observable.create(new OnSubscribe<T>() {
@Override
public void call(Subscriber<? super T> subscriber) {
subscriber.onNext(t);
}
});
}
public RxAsyncHelper(Observable<T> observable){
this.observable = observable;
}
public void subscribe(){
this.observable.observeOn(AndroidSchedulers.mainThread()).subscribe();
}
public void subscribe(Action1<? super T> action){
this.observable.observeOn(AndroidSchedulers.mainThread()).subscribe(action);
}
public void subscribe(Subscriber<? super T> subscriber){
this.observable.observeOn(AndroidSchedulers.mainThread()).subscribe(subscriber);
}
/**
* 运行在子线程
* @param func
* @param <R>
* @return
*/
public <R>RxAsyncHelper<R> runInThread(Func1<? super T, ? extends R> func){
return new RxAsyncHelper(this.observable.observeOn(Schedulers.io()).map(func));
}
/**
* 运行在主线程
* @param func
* @param <R>
* @return
*/
public <R>RxAsyncHelper<R> runOnMainThread(Func1<? super T, ? extends R> func){
return new RxAsyncHelper(this.observable.observeOn(AndroidSchedulers.mainThread()).map(func));
}
/**
* 绑定activity的生命周期函数,activity结束时observable也释放
* @param rxActivity
* @return
*/
public RxAsyncHelper bindToLifeStyle(RxAppCompatActivity rxActivity){
this.observable.compose(rxActivity.bindToLifecycle());
return this;
}
/**
* 绑定fragment的生命周期函数,fragment结束时observable也释放
* @param rxFragment
* @return
*/
public RxAsyncHelper bindToLifeStyle(RxFragment rxFragment){
this.observable.compose(rxFragment.bindToLifecycle());
return this;
}
}
使用:
RxAsyncHelper rxAsyncHelper = new RxAsyncHelper("");
rxAsyncHelper.runInThread(new Func1() {
@Override
public Object call(Object o) {
//异步线程
return null;
}
}).runOnMainThread(new Func1() {
@Override
public Object call(Object o) {
updateView();//UI线程
return null;
}
}).subscribe();