Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between interval() and repeatWhen() for polling from an Observable in intervals

Tags:

rx-java

Is there any difference between:

Observable<String> observable = Observable
        .interval(0, 1, TimeUnit.SECONDS)
        .flatMap(new Func1<Long, Observable<String>>() {
            @Override
            public Observable<String> call(Long aLong) {
                return Observable.just("MyString");
            }
        })

and:

Observable<String> observable = Observable.just("MyString")
        .repeatWhen(new Func1<Observable<? extends Void>, Observable<?>>() {
            @Override
            public Observable<?> call(Observable<? extends Void> completed) {
                return completed.delay(1, TimeUnit.SECONDS);
            }
        })

The second is cleaner but in practical terms and considering backpressure, will these two solutions behave the same way?

like image 757
Anyonymous2324 Avatar asked Mar 03 '16 11:03

Anyonymous2324


1 Answers

Depending on your source observable (which in this case is just("MyString")) there could be a couple differences:

  1. interval() will run every second (if possible), whereas repeatWhen() will always delay() by 1 second. For just() this doesn't matter, but if your source takes a while to run (e.g. 500ms) then you will see a difference in timing: interval() will resubscribe every 1,000ms, but repeatWhen(delay()) will run every 1,500ms (500ms output + 1,000ms delay).

    If your source takes longer than a second, then there will be no pause between each resubscription with interval(), since it'll just wait until the previous flatMap() is done before executing another one!

  2. If you use a Scheduler within the flatMap() then you can achieve some parallelization that's not possible with repeatWhen(). Again, this doesn't really matter for just(), but it would for a long-running Observable. For more on that, check out this great article.

I'm not confident these are all the differences between the two, someone who is more familiar with RxJava's internals could probably point more out.

like image 178
Dan Lew Avatar answered Jan 03 '23 20:01

Dan Lew