我正在和Rx一起玩,而且那些东西并没有像我期望的那样表现出来。有关要实现的目标的详细评论的原始代码是here(请参阅groupOperations())。
public static void lostLastItemVersion1() {
rangeWhichNeverCompletes(3).publish(stream ->
stream.buffer(
Observable.amb(
stream.debounce(100L, TimeUnit.MILLISECONDS),
stream.skip(2))
.first()
.repeatWhen(observable -> observable)))
.subscribe(operations ->
System.out.println("Buffer size: " + operations.size()));
try {
Thread.sleep(1000L);
System.out.println("FINISH");
} catch (InterruptedException e) {
}
}
private static Observable<Integer> rangeWhichNeverCompletes(int limit) {
return Observable.create(emitter -> {
for (int i = 1; i <= limit; i++) {
emitter.onNext(i);
}
},
Emitter.BackpressureMode.BUFFER);
}
预期产出:
Buffer size: 3
FINISH
实际输出:
Buffer size: 2
FINISH
最后一项未缓冲......
更改代码的结果令人不满意:
public static void lostLastItemVersion2() {
ConnectableObservable<Integer> stream = rangeWhichNeverCompletes(3)
.publish();
stream.buffer(
Observable.amb(
stream.debounce(100L, TimeUnit.MILLISECONDS),
stream.skip(2))
.first()
.repeatWhen(observable -> observable))
.subscribe(operations ->
System.out.println("Buffer size: " + operations.size()));
stream.connect();
try {
Thread.sleep(1000L);
System.out.println("FINISH");
} catch (InterruptedException e) {
}
}
调试时我发现buffer()和skip()的组合会产生奇怪的输出:
public static void case1() {
Observable.range(1, 15)
.publish(stream -> stream.buffer(
stream.skip(2)
.first()
.repeatWhen(observable -> observable)))
.subscribe(operations ->
System.out.println("Buffer size: " + operations.size()));
try {
Thread.sleep(1000L);
System.out.println("FINISH");
} catch (InterruptedException e) {
}
}
输出:
Buffer size: 2
Buffer size: 4
Buffer size: 3
Buffer size: 3
Buffer size: 3
Buffer size: 0
FINISH
据我所知,0的最后一次发射是可以的
完成源或边界Observable导致返回的Observable发出最新的缓冲区并完成。
但为什么前两次排放的缓冲区大小为2和4?为什么不总是3?
有没有人可以形容我发生了什么?这是一个错误/功能/预期的行为?任何干净的解决方法?