in Programming, Tips

Experiments with interval based observables

Similar to timer, RxJava provides an option for creating a scheduled Observable that emits indefinitely (until completed) during specified time intervals. The resulting Observable emits events of type Long, starting from 0. The interval option is perfect for creating simple scheduled jobs.

It is important to note that by default, an interval Observable will block on long-running operations to keep the order of the events sequential. For example, the following piece of code will take 1 second every time, instead of the predefined 300 ms, despite the fact that we have specified a concurrent scheduler for the interval to run on.

        .interval(300, TimeUnit.MILLISECONDS,
            .doOnNext(new Action1<Long>() {
                public void call(Long aLong) {
                    System.out.println("action thread: " + Thread.currentThread());
                    try {
                    } catch (InterruptedException e) {
            // ...

In most cases, this makes logical sense. If your job is taking more time than expected, you want it to finish, before you schedule a new one.