RxJava2:使用热源扫描 - 总是落后一个值?

时间:2017-06-23 10:46:04

标签: rx-java rx-java2

我无法理解scan与热源相结合的行为 - 我首先在制作环境中体验过这种情况,但我很幸运能够在玩具示例中重现效果。

我们走了:

    PublishRelay<Integer> source = PublishRelay.create();

    Flowable<Integer> sink = source.toFlowable(BackpressureStrategy.LATEST)
            .scan(1, new BiFunction<Integer, Integer, Integer>() {
                @Override
                public Integer apply(Integer integer, Integer integer2) throws Exception {
                    int result = integer + integer2;
                    System.out.println(String.format("%d + %d = %d", integer, integer2, result));
                    return result;
                }
            })
            .share();

    Thread.sleep(2_000);
    System.out.println(String.format("sending: %d", 2));
    source.accept(2);

    System.out.println(String.format("subscribing now"));
    sink.subscribe(
            new Consumer<Integer>() {
                @Override
                public void accept(Integer integer) throws Exception {
                    System.out.println(String.format("onNext: %d", integer));
                }
            }
    );
    System.out.println(String.format("subscribing done"));

    Thread.sleep(2_000);
    System.out.println(String.format("sending: %d", 3));
    source.accept(3);

    Thread.sleep(2_000);
    System.out.println(String.format("sending: %d", 4));
    source.accept(4);

    Thread.sleep(2_000);
    System.out.println(String.format("done"));

此代码的输出为:

sending: 2
subscribing now
subscribing done
sending: 3
1 + 3 = 4
onNext: 1
sending: 4
4 + 4 = 8
onNext: 4
done

现在,我的问题是:为什么总是落后一个价值?为什么不:

sending: 2
subscribing now
subscribing done
sending: 3
1 + 3 = 4
onNext: *4*
sending: 4
4 + 4 = 8
onNext: *8*
done

而且,我能做些什么呢? scan本身至少有一个订阅者后,我是否需要确保源只会发出新项

0 个答案:

没有答案