Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If I am chaining multiple operators using RxJava do i need to call .subscribeOn() for each of them?

Tags:

java

rx-java

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?

like image 644
Sree Avatar asked Dec 10 '15 18:12

Sree


1 Answers

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.

like image 195
akarnokd Avatar answered Sep 23 '22 10:09

akarnokd