如果我使用RxJava链接多个运算符,我需要为每个运算符调用.subscribeOn()吗?

Sre*_*ree 5 java rx-java

这是一个例子:

 return ApiClient.getPhotos()
            .subscribeOn(Schedulers.io())
            .map(new Func1<APIResponse<PhotosResponse>, List<Photo>>() {
                      @Override
                      public List<Photo> call(CruiselineAPIResponse<PhotosResponse> response) {
                             //convert the photo entities into Photo objects
                             List<ApiPhoto> photoEntities = response.getPhotos();
                             return Photo.getPhotosList(photoEntities);
                        }
             })
            .subscribeOn(Schedulers.computation())
Run Code Online (Sandbox Code Playgroud)

我是否需要两者.subscribeOn(Schedulers.computation()),.subscribeOn(Schedulers.computation())因为它们适用于不同的Observable?

aka*_*okd 5

无需多次subscribeOn通话; 在这种情况下,第二次调用在功能上是无操作,但在序列的持续时间内仍保留在某些资源上.例如:

Observable.just(1)
.map(v -> Thread.currentThread())
.subscribeOn(Schedulers.io())
.subscribeOn(Schedulers.computation())
.toBlocking()
.subscribe(System.out::println)
Run Code Online (Sandbox Code Playgroud)

会印出类似的东西 ... RxCachedThreadScheduler-2

您可能需要observeOn(Schedulers.computation())将每个值(在本例中为List对象)的观察移动到另一个线程.

  • 所以你需要`getPhotos().subscribeOn(io).observeOn(computation).map(...).observeOn(mainThread)`.那应该在`IO`上执行你的API调用,你在`calculate`上的映射,并在`main`线程上给你输出.请注意,所有这些都假定`getPhotos()`是冷的(即仅通过诸如`defer`之类的机制开始在订阅上运行). (5认同)
  • 如果它很热,那么在应用`subscribeOn`之前,它会在你调用方法后立即发出网络请求.[我在这个答案中解释一下](http://stackoverflow.com/a/29675387/12170870). (2认同)