Search code examples
javarx-java2

Why interval doesn't emit anything?


Why this code doesn't emit anything:

Observable<Long> observable1 = Observable.interval(3, 1000, TimeUnit.MILLISECONDS);
observable1.subscribe(l -> System.out.println(l));

Solution

  • intervall() operates on Scheduler.computation(), which allocates a new thread. Your program terminates before the new thread has a chance to run. You can solve that by suspending the main thread for a while.

    Observable<Long> observable1 = Observable.interval(3, 1000, TimeUnit.MILLISECONDS);
    observable1.subscribe(l -> System.out.println(l));
    
    try {
        Thread.sleep(5000);
    }
    catch(InterruptedException e) { }
    

    Now, you will see some output.