[英]Loop Nesting List RxJava2
我有一个对象A的列表,在每个AI中都有一个对象B的列表。
这是我想做的:
在使用RxJava遍历List<A>
同时,我希望能够循环内部列表并对List<B>
进行一些过滤,最后,我想将过滤后的List<B>
到原始父对象List<A>
。
可以在不中断链条的情况下进行此操作?
像这个例子:
class A {
int mAId;
List<B> mBList;
}
class B{
int mId;
}
public void loop(List<A> list){
Observable.fromIterable(list)
.flatMapIterable(objs-> objs.mBList)
.filter("filtering each b")
.toList()
.map("add back the list of b to the right a")
.subscribe()
}
我的意见:
public void loop(List<A> list){
List<FromObject> innerList;
list.forEach(e->{
innerList=e.getInnerList();
innerList.forEach(in->{
<apply your filter here>
<for example>
if(in.getNumber()>0)
innerList.remove(in);
}
}
}
希望这会有所帮助
是的,您可以通过嵌套反应流来实现它:
List<List<Integer>> listOfLists = Arrays.asList(
Arrays.asList(0, 1, 2, 3, 4, 5),
Arrays.asList(6, 7, 8, 9, 10, 11),
Arrays.asList(12, 13, 14, 15, 16, 17),
Arrays.asList(18, 19, 20, 21, 22, 23)
);
Observable.fromIterable(listOfLists)
.flatMap((innerList) -> {
return Observable.fromIterable(innerList)
.filter((value) -> value % 2 == 0)
.toList()
.toObservable();
})
.toList()
.subscribe(listOfListsFiltered -> {
for (List<Integer> innerList : listOfListsFiltered) {
for (Integer value : innerList) {
System.out.print(value + ", ");
}
System.out.println();
}
});
}
为将来的读者或灵感更好的答案。 还有另一种方法
public static class A {
int id;
List<B> mBList;
}
public static class B {
int id;
}
public void test() {
Observable.just(Arrays.asList(new A(), new A(), new A()))
.flatMapIterable(a -> a)
.map(a -> {
a.mBList = Observable.fromIterable(a.mBList)
.distinct()
.toList()
.blockingGet();
return a;
});
}
我终于找到了这个问题的答案:
class A(val filterable: Boolean = random.nextBoolean())
class B(val name: String = random.nextInt().toString(), val listOfA: List<A> = listOf(A(), A(), A(), A(), A(), A()))
@Test
fun rxTest() {
Observable.fromIterable(listOf(B(), B(), B(), B(), B(), B(), B()))
.compose {
it.publish<B> { publish ->
val filteredList = publish.flatMapIterable { it.listOfA }
.filter {
it.filterable
}
.toList()
.toObservable()
Observable.zip<B, List<A>, B>(publish, filteredList, BiFunction<B, List<A>, B> { b, listOfA ->
B(b.name, listOfA)
})
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.