如何使平面地图在后台线程上执行

我正在使用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文档,不在任何后台线程上运行。我的问题是,如何确保整个方法在后台运行。flatMapgetMyData()


答案 1


我只是添加之前,它的工作原理!observeOn(Schedulers.newThread())flatMap


答案 2

这只会将管道中的一个步骤移动到后台线程:

Observable<Integer> vals = Observable.range(1,10);

vals.flatMap(val -> Observable.just(val)
            .subscribeOn(Schedulers.computation())
            .map(i -> intenseCalculation(i))
).subscribe(val -> System.out.println(val));

最初在这里回答:https://stackoverflow.com/a/35429084/2908525


推荐