Reputation: 237
public static void main(String[] args) throws InterruptedException {
Observable.range(1, 3)
.subscribeOn(Schedulers.computation())
.map(i-> compute(i))
.subscribe(i -> {
System.out.println(i);
});
System.out.println("last line");
}
public static int compute(Integer i) {
try {
System.out.println("compute integer i: " + i);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 10*i;
}
Output:
last line
compute integer i: 1
If the main method would start a usual thread we would see the complete output:
public static void main(String[] args) {
Thread a=new Thread(() -> {
compute(1);
compute(2);
compute(3);
});
a.start();
System.out.println("last line");
}
Output:
last line
compute integer i: 1
compute integer i: 2
compute integer i: 3
Why doesnt the main thread wait for the completion of Schedulers.computation() thread whereas it waits for the completion of the usual new Thread()?
Upvotes: 1
Views: 257
Reputation: 69997
This is by design. RxJava standard schedulers use daemon threads so that they don't prevent the JVM from quitting. That means you have to keep non-daemon thread(s) running in some form if you want the work on schedulers to finish.
Upvotes: 2