Search code examples
javarx-javarx-java2

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

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

Screenshot


Solution

  • 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.