当我订阅另一个schduler时,subscibe不再工作了

时间:2016-08-07 02:31:20

标签: android rx-java

*下面的代码没有打印任何内容,让我困惑* 当我删除subscribeon,它工作,打印我想要的

Observable observable = Observable.<String>create(subscriber -> {
                try {
                    subscriber.onNext("1");
                    System.out.println(" current thread is " + Thread.currentThread().getName());
                    Thread.sleep(100);
                    subscriber.onNext("2");
                    Thread.sleep(300);
                    subscriber.onNext("3");
                    Thread.sleep(1000);
                    subscriber.onNext("4");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
    );

    observable.subscribeOn(Schedulers.io()).timeInterval().observeOn(Schedulers.immediate()).subscribe(n -> System.out.println(((TimeInterval) n).getIntervalInMilliseconds()
                    + "   value is  " + ((TimeInterval) n).getValue()),
            e -> System.out.println("onerror " + e),
            () -> System.out.println("oncomplete "));

1 个答案:

答案 0 :(得分:1)

主线程在subscribeOn生效之前退出,尝试在主线程中休眠或使用toBlocking().subscribe(...)。另请注意,Schedulers.immediate()在接收到值的同一线程上执行任务,并在组装序列的线程上执行