使用调度程序时,System.out.println 在 RxJava 中不打印任何内容 [英] When using Schedulers, System.out.println prints nothing in RxJava

查看:114
本文介绍了使用调度程序时,System.out.println 在 RxJava 中不打印任何内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在摆弄 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.

我注意到,当我在最后使用 Thread.sleep() 阻塞主线程时,System.out.println 会打印正确的值 - 1 2 3:

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 使用 daemon 线程.所以你的应用程序在你的 Observable 开始发射之前就完成了.检查起来很容易,只需通过 Scheduler 返回非 daemon 线程,您将看到您的输出值:

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));

取消注释行 result.setDaemon(true); 和值将不会被打印.

Uncomment the line result.setDaemon(true); and values will not be printed.

这篇关于使用调度程序时,System.out.println 在 RxJava 中不打印任何内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆