I'm fiddling around with RxJava and Schedulers. I implemented a very simple stream with a scheduler:
Observable.just(1, 2, 3)
.doOnNext(v -> Thread.currentThread().getName())
.subscribeOn(Schedulers.newThread())
.subscribe(v -> System.out.println(v));
The example above prints nothing in the console.
I noticed, that when I block the main thread at the end using ie Thread.sleep(), System.out.println prints proper values - 1 2 3:
Observable.just(1, 2, 3)
.doOnNext(v -> Thread.currentThread().getName())
.subscribeOn(Schedulers.newThread())
.subscribe(v -> System.out.println(v));
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
Can someone help me understand this behaviour?
RXJava
uses daemon
threads. So your app just finishes before your Observable
starts emission. It's quite easy to check, just pass Scheduler
which returns non daemon
thread and you will see your output values:
Scheduler scheduler = Schedulers.from(Executors.newCachedThreadPool(new ThreadFactory() {
@Override public Thread newThread(Runnable r) {
Thread result = new Thread(r);
//result.setDaemon(true);
return result;
}
}));
Observable.just(1, 2, 3)
.subscribeOn(scheduler)
.subscribe(v -> print(v));
Uncomment the line result.setDaemon(true);
and values will not be printed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.