目前我正在学习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();
}
}
}
答案 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);
}