Search code examples
rx-javareactive-programmingrx-java2

Ambiguous Behaviour of RxJava flatMap Operator


public class MainActivity1 extends AppCompatActivity {
    private String LOG_TAG = "MY_LOG";
    private CompositeDisposable compositeDisposable = new CompositeDisposable();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        compositeDisposable.add(getObservable().subscribeWith(getObserver()));
    }

    private Observable<Integer> getObservable(){
        return Observable.just(1,2,3).flatMap(lValue -> Observable.just(lValue,lValue,lValue));
    }

    private DisposableObserver<Integer> getObserver(){
        return new DisposableObserver<Integer>() {
            @Override
            public void onNext(@NonNull Integer s) {
                Log.d(LOG_TAG,"onNext : " + s);
            }

            @Override
            public void onError(@NonNull Throwable e) {
                Log.d(LOG_TAG,"onError");
            }

            @Override
            public void onComplete() {
                Log.d(LOG_TAG,"onComplete");
            }
        };
    }
}

The Output of above code is :

D/MY_LOG: onNext : 1
D/MY_LOG: onNext : 1
D/MY_LOG: onNext : 2
D/MY_LOG: onNext : 2
D/MY_LOG: onNext : 3
D/MY_LOG: onNext : 3
D/MY_LOG: onComplete

Here 1, 2 and 3 are printed twice each time. The expected behavior should be 1, 2, and 3 being printed thrice each time as three values have been passed inside just operator inside flatMap operator. Does anyone know why this weird behavior is observed?


Solution

  • The code seems to be fine. It could be an issue with the Log also sometimes that, the log may not print all the values if you are frequently printing. Try adding a doOnNext and see if the just emits all the values

     Observable.just(lValue,lValue,lValue).doOnNext(new Consumer<Integer>() {
            @Override
            public void accept(Integer integer) throws Throwable {
                Log.d(TAG, "accept: "+ integer);
                // or use debugger to check the value
            }
        })