如何使平面地图在后台线程上执行
2022-09-04 22:51:38
我正在使用Retrofit和RxJava来执行一些后台任务。代码如下所示:
public class MyLoader{
public Observable<MyData> getMyData(){
return setupHelper().flatMap(new Func1<MyHelper, Observable<MyData>>() {
@Override
public Observable<MyData> call(MyHelper myHelper) {
return queryData(myHelper);
}
});
}
private Observable<MyData> queryData(MyHelper myHelper){
...
}
private Observable<MyHelper> setupHelper(){
return Observable.create(new Observable.OnSubscribe<MyHelper>() {
@Override
public void call(final Subscriber<? super MyHelper> subscriber) {
try{
MyHelper helper = makeRetrofitCall();//Using Retrofit blocking call to get some data
subscriber.onNext(helper);
subscriber.onCompleted();
}catch(RetrofitError e){
subscriber.onError(e)
}
}
}
}
}
这在“改造错误”中失败,因为以下行中的异常:NetworkOnMainThread
MyHelper helper = makeRetrofitCall();//Using Retrofit blocking call to get some data
订阅我的 Observable:
myLoader.getMyData()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<MyData>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(MyData inventory) {
}
});
根据Rx文档,不在任何后台线程上运行。我的问题是,如何确保整个方法在后台运行。flatMap
getMyData()