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

喜夏-厌秋 提交于 2019-12-24 00:28:04

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/35234211/when-using-schedulers-system-out-println-prints-nothing-in-rxjava

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!