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 i.e. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With