RX Java – the difference between interval() and repeatwhen() for polling from observable in the interval
What is the 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 actually considering the back pressure, do the two solutions behave in the same way?
Solution
Depending on your source observable (in this case, just ("mystring")), there may be some differences:
>Interval () will run once per second (if possible), and repeatwhen () will always be delayed by () 1 second For just (), it doesn't matter, but if your source takes a period of time to run (for example, 500ms), you will see the difference in time: interval () will re subscribe every 1000ms, but repeatwhen (delay ()) will run every 1500ms (500ms output 1000ms delay)
If your source takes more than one second, there will be no pause between each subscription and interval(), because it will only wait until the previous flatmap() completes before executing another! > If you use a scheduler in flatmap (), you can implement some parallelization that repeatwhen () cannot Again, this is not important for just (), but it applies to long-running observable For more information, see this great article
I don't believe there is a difference between the two. People who are more familiar with rxjava may point out more