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?
Depending on your source observable (which in this case is just("MyString")
) there could be a couple differences:
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With