Does Observable run on computation thread by default in RxJava

Currently I am learning RxJava and just got stuck with a basic doubt. See the below code. I am not using any subscribeOn(). Will the below code execute on main thread or on computation thread?

import io.reactivex.Observable;
import java.util.concurrent.TimeUnit;

public class Launcher {
      public static void main(String[] args) {
        Observable<Long> secondIntervals =
          Observable.interval(1, TimeUnit.SECONDS);

        secondIntervals.subscribe(s -> System.out.println(s));

        /* Hold main thread for 5 seconds
        so Observable above has chance to fire */
        sleep(5000);
      }

      public static void sleep(long millis) {
        try {
          Thread.sleep(millis);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
}

Answer

It will execute on the computation thread, see this modified version of you main method:

public static void main(String[] args) {
    Observable<Long> secondIntervals =
            Observable.interval(1, TimeUnit.SECONDS);

    secondIntervals.subscribe(s -> System.out.println("Observable thread id: "
                                                      + Thread.currentThread().getId()));

    System.out.println("Main thread id: " + Thread.currentThread().getId());

    /* Hold main thread for 5 seconds
    so Observable above has chance to fire */
    sleep(5000);
}

Leave a Reply

Your email address will not be published. Required fields are marked *