List<Integer> list = new ArrayList<Integer>();
for(int j=1;j<=3;j++)
list.add(j);
Observable<Integer> observable = Observable.fromIterable(list)
.replay()
.autoConnect();
observable.subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Exception {
Log.v("consumer1:", ""+integer);
}
});
observable.subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Exception {
Log.v("consumer2:", ""+integer);
}
});
observable.subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Exception {
Log.v("consumer3:", ""+integer);
}
});
当我运行上面的代码时,我得到以下输出:
consumer1:: 1
consumer1:: 2
consumer1:: 3
consumer2:: 1
consumer2:: 2
consumer2:: 3
consumer3:: 1
consumer3:: 2
consumer3:: 3
我期望重播实际上是“重播”以前发生的所有历史记录。所以我期望发出所有以前发生的流。特别是这是我期望的输出:
//first time nothing to replay so just do the work
consumer1:: 1
consumer1:: 2
consumer1:: 3
//replay consumer1 stream:,
consumer2:: 1
consumer2:: 2
consumer2:: 3
//already replayed now do the work
consumer2:: 1
consumer2:: 2
consumer2:: 3
//replay consumer1 stream:
consumer3:: 1
consumer3:: 2
consumer3:: 3
//replay consumer2 stream:
consumer3:: 1
consumer3:: 2
consumer3:: 3
//now do the work
consumer3:: 1
consumer3:: 2
consumer3:: 3
这是我期望重放发生的事情。我究竟做错了什么 ?它像它甚至没有以我现在的方式工作。
答案 0 :(得分:1)
不确定为什么要执行这种奇特的行为,但是您可以重复使用的数字越来越多:
List<Integer> list = new ArrayList<Integer>();
for (int j = 1; j <= 3; j++) {
list.add(j);
}
AtomicInteger count = new AtomicInteger();
Observable<Integer> observable =
Observable.defer(() -> {
Observable.fromIterable(list)
.replay()
.autoConnect()
.repeat(count.incrementAndGet());
});
observable.subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Exception {
Log.v("consumer1:", ""+integer);
}
});
observable.subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Exception {
Log.v("consumer2:", "" + integer);
}
});
observable.subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Exception {
Log.v("consumer3:", ""+integer);
}
});