Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava2 filter List<Object>

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;
}

I want to only get the list of items where the value2 is 10.

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());

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.

I'm pretty new to RxJava and RxJava2 and seems like I'm missing something basic here?

TIA

like image 875
Bootstrapper Avatar asked Feb 13 '17 22:02

Bootstrapper


1 Answers

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(...);
like image 180
akarnokd Avatar answered Oct 21 '22 09:10

akarnokd