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
You can unroll the list and then collect up those entries that passed the filter:
You may take a look at the below. It demonstrates the ways to print just the filtered objects OR the lists that contain filtered objects. Here the filtering logic is to retain the
org.apache.commons.lang3.tuple.Pair
s that have even numbers in right.Output with contents of observable:
Output to contain only filtered objects:
Output to contain the lists that contain only filtered objects.