*下面的代码没有打印任何内容,让我困惑* 当我删除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 "));
答案 0 :(得分:1)
主线程在subscribeOn
生效之前退出,尝试在主线程中休眠或使用toBlocking().subscribe(...)
。另请注意,Schedulers.immediate()
在接收到值的同一线程上执行任务,并在组装序列的线程上执行不。