简体   繁体   English

为什么 RxJava2 不向线程发送数据

[英]Why RxJava2 does not emitter data to the thread

I have read the RxJava's doc.我已经阅读了 RxJava 的文档。 and try the demo below: The Output is d = [0]d = false并尝试下面的演示:Output is d = [0]d = false

May I know the reason that: why the data does not emitter to the Observer我可以知道原因:为什么数据不发射到Observer

RxJava version: 2.2.6 RxJava 版本: 2.2.6

        Observable.just("aa","bbb")
                .observeOn(Schedulers.newThread())
                .map(s -> {
                    System.out.println("s = [" + s + "]");
                    return s.toUpperCase();
                })
                .subscribeOn(Schedulers.single())
                .observeOn(Schedulers.io())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        System.out.println("d = [" + d + "]"+"d = "+ d.isDisposed());
                    }

                    @Override
                    public void onNext(String s) {
                        System.out.println("s = [" + s + "]");
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

With all the thread switches you have added to your subscription your subscription is not running on the main thread anymore.使用您添加到订阅中的所有线程切换,您的订阅不再在主线程上运行。 This also means that nothing is stopping the main thread anymore and you application quits before it could print the data you want.这也意味着不再停止主线程,并且您的应用程序在它可以打印您想要的数据之前退出。

For testing purposes you can add a Thread.sleep(1000);出于测试目的,您可以添加Thread.sleep(1000); at the end of your main() method (where I suppose you have added this code).在你的main()方法的末尾(我想你已经添加了这段代码)。 Then you will see the output from the System.out.println() statements.然后您将在System.out.println()语句中看到 output。 Other solutions are to not use subscribeOn() or observeOn() and stay on the current thread.其他解决方案是不使用subscribeOn()observeOn()并留在当前线程上。 Also, you can use blockingSubscribe() to wait for the subscription to finish before continuing on the main thread.此外,您可以使用blockingSubscribe()等待订阅完成,然后再继续主线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM