Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using Schedulers, System.out.println prints nothing in RxJava

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?

like image 447
tomdavies Avatar asked Oct 29 '25 01:10

tomdavies


1 Answers

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.

like image 200
eleven Avatar answered Oct 30 '25 17:10

eleven



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!