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

青春壹個敷衍的年華 提交于 2020-03-16 07:25:09

问题


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

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


回答1:


By default the timer operator is executed in a different Thread (in the computation thread pool) and your main thread is exited just after calling the subscribe and shutdowns the VM.

Yo have different solutions for this.

  1. Add a Thread.sleep(value > 2000) after your subscribe
  2. Call blockingSubscribe instead of subscribe. The current thread (main) blocks until the upstream terminates
  3. Change the time scheduler to trampoline :
    Observable.timer(2, TimeUnit.SECONDS, Schedulers.trampoline())

From the documentation

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.



来源:https://stackoverflow.com/questions/59005142/why-is-there-no-information-output-from-the-console-after-two-seconds-rxjava

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!