ThrottleLast in RxJava : Unexpected Behavior

96 Views Asked by At

I faced the unexpected behavior when I tested the sample code as follows.

@Test
public void test_throttleLast() {

    Observable.fromArray("0", "1", "2", "3", "4")
            .zipWith(Observable.interval(1000L, TimeUnit.MILLISECONDS), new BiFunction<String, Long, String>() {

                @Override
                public String apply(String s, Long index) throws Exception {
                    System.out.println("apply : [" + index + "]");
                    return s;
                }
            })
            .throttleLast(2000L, TimeUnit.MILLISECONDS)
            .subscribe(new Observer<String>() {
                @Override
                public void onSubscribe(Disposable d) {
                }

                @Override
                public void onNext(String s) {
                    System.out.println("## result : " + s);
                }

                @Override
                public void onError(Throwable e) {
                    System.out.println("## onError : " + e);
                }

                @Override
                public void onComplete() {
                    System.out.println("## onComplete");
                }
            });

    try {
        Thread.sleep(10000);
    } catch (InterruptedException ignored) {
    }
}

My expectation is as follows

apply : [0]
apply : [1]
## result : 1
apply : [2]
apply : [3]
## result : 3
apply : [4]
## result : 4
## onComplete 

However the real output varies every time when it runs as follows

apply : [0]
apply : [1]
## result : 1
apply : [2]
## result : 2    <-- weird
apply : [3]
apply : [4]
## onComplete
apply : [0]
## result : 0    <-- weird
apply : [1]
apply : [2]
apply : [3]
## result : 3     <-- weird
apply : [4]
## onComplete
apply : [0]
apply : [1]
## result : 1
apply : [2]
apply : [3]
## result : 2    <-- weird
apply : [4]
## onComplete

I get confuse why it has different results; Moreover, onComplete is called even though not emitting '4'.

What's the reason for that?

0

There are 0 best solutions below