为什么两秒后控制台没有信息输出---Rxjava

Why is there no information output from the console after two seconds --- Rxjava

public class RxJavaTest {
    public static void main(String[] args) {
        Observable.timer(2, TimeUnit.SECONDS).subscribe(new Consumer<Long>() {
            @Override
            public void accept(Long aLong) throws Exception {
                System.out.println("timer: accept " + aLong);
            }
        });
    }
}

为什么两秒后控制台没有信息输出?

默认情况下,timer 运算符在不同的线程(在计算线程池中)中执行,您的 main 线程在调用订阅并关闭 VM 后立即退出。

你有不同的解决方案。

  1. subscribe
  2. 后添加 Thread.sleep(value > 2000)
  3. 调用 blockingSubscribe 而不是 subscribe。当前线程(主线程)阻塞直到上游终止
  4. 将时间安排程序更改为蹦床:
    Observable.timer(2, TimeUnit.SECONDS, Schedulers.trampoline())

来自文档

The default implementation's {@link Scheduler#scheduleDirect(Runnable)} methods execute the tasks on the current thread without any queueing and the timed overloads use blocking sleep as well.