默认情况下,Observable是否在RxJava中运行在计算线程上

时间:2018-05-20 17:32:34

标签: java rx-java

目前我正在学习RxJava并且遇到了基本的疑问。请参阅以下代码。我没有使用任何subscribeOn()。下面的代码会在主线程或计算线程上执行吗?

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

1 个答案:

答案 0 :(得分:1)

它将在计算线程上执行,请参阅此main方法的修改版本:

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);
}