I've been making use of Observable.fromEmitter()
as a fantastic alternative to Observable.create()
. I've recently run into some weird behaviour and I can't quite work out why this is the case. I'd really appreciate someone with some knowledge on backpressure and schedulers taking a look at this.
public final class EmitterTest {
public static void main(String[] args) {
Observable<Integer> obs = Observable.fromEmitter(emitter -> {
for (int i = 1; i < 1000; i++) {
if (i % 5 == 0) {
sleep(300L);
}
emitter.onNext(i);
}
emitter.onCompleted();
}, Emitter.BackpressureMode.LATEST);
obs.subscribeOn(Schedulers.computation())
.observeOn(Schedulers.computation())
.subscribe(value -> System.out.println("Received " + value)); // Why does this get stuck at "Received 128"
sleep(10000L);
}
private static void sleep(Long duration) {
try {
Thread.sleep(duration);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
The output of this application is
Received 1
Received 2
...
Received 128
Then it remains stuck at 128 (assumedly because this is RxJava's default buffer size).
If I change the mode specified in fromEmitter()
to BackpressureMode.NONE
, then the code works as intended. If I remove the call to observeOn()
, it also works as intended. Is anyone able to explain why this is the case?