J. K. J. K. - 4 months ago 11
Android Question

Why does interval operator in RxJava change the results from flatMap

I am running this code:

private void concatenatedSets() {
Observable<String> concatenatedSets =
Observable.just("1/5/8", "1/9/11/58/16/", "9/15/56/49/21");

concatenatedSets.flatMap(s -> Observable.from(s.split("/")))
.map(s -> Integer.valueOf(s))
.interval(200, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<Long>() {
@Override
public void onCompleted() {

}

@Override
public void onError(Throwable e) {

}

@Override
public void onNext(Long aLong) {
tvCounter.setText(String.valueOf(aLong));
}
});
}


The expected output would be

1
5
8
1
9
11
58
16
9
15
56
49
21


However, all I get is an endless session of counting from 1 to infinity as in 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12...

I think the problem came after I added

.interval(200, TimeUnit.MILLISECONDS)


but I don't know why.

Answer

interval() is a factory method on Observable that gives you a sequence of values, starting from 0, periodically. It is a source operator that should be statically called like Observable.interval() but you called it on an instance. Most IDEs should warn you about invoking a static method on an instance because usually something different will happen than you expect.

I suspect you want to span out values separated by 200 ms; there is no standard operator for that in RxJava but is a common question here on SO (and should have an answer already).