RxJava2 过滤器列表<对象> [英] RxJava2 filter List<Object>
问题描述
我正在尝试使用 RxJava2 过滤列表,以便列表中的每个项目(对象)都应该通过验证检查,并且我得到一个结果列表,其中只有通过该测试的项目.例如,如果我的对象具有以下结构,
I'm trying to filter a List with RxJava2 such that each item (object) in the list should pass a validation check and I get a resulting List with only items that pass that test. For instance if my Object had the following structure,
class MyClassA {
int value1;
int value2;
}
我只想获取 value2
为 10 的项目列表.
I want to only get the list of items where the value2
is 10.
我有一个 API 调用函数,它返回一个列表的 Observable,即 Observable
如下,>
I have an API call function that returns an Observable of List, i.e. Observable<List<MyClassA>>
as follows,
apiService.getListObservable()
.subscribeOn(Schedulers.io)
.observeOn(AndroidSchedulers.mainThread());
并且我想要过滤输出,所以我尝试在上面添加一个 .filter()
操作符,但它似乎需要一个 Predicate
而不仅仅是一个 >
MyClassA
对象,我可以用它检查并只允许 value2 == 10
的对象.
and I would like to have the output filtered, so I tried adding a .filter()
operator to the above but it seems to require a Predicate<List<MyClassA>>
instead of just a MyClassA
object with which I can check and allow only ones where value2 == 10
.
我对 RxJava 和 RxJava2 还很陌生,似乎我在这里遗漏了一些基本的东西?
I'm pretty new to RxJava and RxJava2 and seems like I'm missing something basic here?
TIA
推荐答案
您可以展开列表,然后收集通过过滤器的条目:
You can unroll the list and then collect up those entries that passed the filter:
apiService.getListObservable()
.subscribeOn(Schedulers.io)
.flatMapIterable(new Function<List<MyClassA>, List<MyClassA>>() {
@Override public List<MyClassA> apply(List<MyClassA> v) {
return v;
}
})
.filter(new Predicate<MyClassA>() {
@Override public boolean test(MyClassA v) {
return v.value2 == 10;
}
})
.toList()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(...);
这篇关于RxJava2 过滤器列表<对象>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!