我想链接一个连续的数据流,并创建一个包含过去结果的结果列表。我可以用以下代码完成。有没有办法在rx链外没有变量?谢谢!
- [0]
- [0, 1]
- [0, 1, 2]
- [0, 1, 2, 3]
- [0, 1, 2, 3, 4]
- [0, 1, 2, 3, 4, 5]
final List<Long> list = new ArrayList<>();
Observable
.interval(1, TimeUnit.SECONDS)
.subscribe(new Action1<Long>() {
@Override
public void call(Long number) {
list.add(number);
System.out.println("- " + list);
}
});
Thread.sleep(100000000L);
↓↓↓↓↓↓↓↓↓
Observable
.interval(1, TimeUnit.SECONDS)
.addToPastResultList() // <--- something like this?
.subscribe(new Action1<List<Long>>() {
@Override
public void call(List<Long> list) {
System.out.println("- " + list);
}
});
Thread.sleep(100000000L);
答案 0 :(得分:5)
您正在寻找scan
运营商
Observable.interval(1, TimeUnit.SECONDS)
.scan(new ArrayList<>(), (list, integer) -> {
list.add(integer);
return list;
})
.subscribe(list -> System.out.println(list));
答案 1 :(得分:1)
我正在回答我的问题......看起来我可以创建一个带有私有变量的地图来处理它。
Observable
.interval(1, TimeUnit.SECONDS)
.map(new Func1<Long, List<Long>>() {
private List<Long> list = new ArrayList<>();
@Override
public List<Long> call(Long number) {
list.add(number);
return list;
}
})
.subscribe(new Action1<List<Long>>() {
@Override
public void call(List<Long> list) {
System.out.println("- " + list);
}
});
Thread.sleep(100000000L);