I'm relatively new on RxJava2 and I'm getting some weird behaviors, so it's likely that I'm using the tool on the wrong way.
It's a fairly big project, but I've separated the snippet below as a minimum reproducible code:
Observable
.interval(333, TimeUnit.MILLISECONDS)
.flatMap(new Function<Long, ObservableSource<Integer>>() {
private Subject<Integer> s = PublishSubject.create();
private int val = 0;
@Override public ObservableSource<Integer> apply(Long aLong) throws Exception {
val++;
s.onNext(val);
return s;
}
})
.subscribe(new Consumer<Integer>() {
@Override public void accept(Integer integer) throws Exception {
Log.w("value: %s", integer);
}
});
This code simulates events from my rx-stream using an .interval and a flatMap receive those events "do some processing" and uses a Subject to push results down the stream.
The stream is an ongoing process which will have several several events.
This minimum code is silly because I'm pushing only on the apply callback, but in the real case there're several possible moments that a push can happen and the number of events being received during apply is not the same amount that will be sent via the Subject.
What I expected to see with this code is:
value: 2 // 1 got skipped because onNext is called before there's a subscriber.
value: 3
value: 4
value: 5
value: 6 ... etc
what I actually got is:
value: 2
value: 3
value: 3 // 3 twice
value: 4
value: 4
value: 4 // 4 repeated 3 times
value: 5
value: 5
value: 5
value: 5 // 5 repeated 4 times
value: 6
value: 6
value: 6
value: 6
value: 6 // 6 repeated 5 times
... etc
I've also tried to have an Observable<Integer> o = s.share(); and returning it, or return directly s.share(); with the same results.
I kind of understand why this is happening. The ObservableSource gets subscribed again n again n again so there're more events on every loop.
The question:
How can I achieve my expected behavior?
(in case my expected behavior was not clear, please ask more on the comments)
private Subject<Integer> s = PublishSubject.create();on a different scope if I were in you - BlackbeltFunctionhave its own class. - Budius