5

Here is an example:

 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())

Do I need both .subscribeOn(Schedulers.computation()) and .subscribeOn(Schedulers.computation()) because they are for different Observables?

Sree
  • 2,727
  • 3
  • 29
  • 47

1 Answers1

5

No need for multiple subscribeOn calls; in this case, the second call is functionally a no-op but still holds onto some resources for the duration of the sequence. For example:

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

Will print something like ... RxCachedThreadScheduler-2

You probably need observeOn(Schedulers.computation()) that moves the observation of each value (a List object in this case) to another thread.

akarnokd
  • 69,132
  • 14
  • 157
  • 192
  • How about if I am on Android and I want to eventually update the UI using the list returned from `map()`? UI stuff on android needs to be done on `AndroidSchedulers.mainThread()` which mean i need to use `observeOn(AndroidSchedulers.mainThread()) ` at the end – Sree Dec 10 '15 at 19:56
  • 5
    So for that you'd want `getPhotos().subscribeOn(io).observeOn(computation).map(...).observeOn(mainThread)`. That should perform your API call on `IO`, your mapping on `computation`, and give you your output on the `main` thread. Note that all of this assumes that `getPhotos()` is cold (ie only starts running on subscription, via a mechanism such as `defer`). – Adam S Dec 10 '15 at 21:37
  • 1
    makes sense. why does hot and cold matter? – Sree Dec 10 '15 at 21:45
  • 2
    If it's hot, then it'll make the network request as soon as you call the method, before `subscribeOn` is applied. [I explain things in this answer](http://stackoverflow.com/a/29675387/12170870). – Adam S Dec 10 '15 at 22:02