rx-java Operators filter Operator

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

You can use the filter operator to filter out items from the values stream based on a result of a predicate method.

In other words, the items passing from the Observer to the Subscriber will be discarded based on the Function you pass filter, if the function returns false for a certain value, that value will be filtered out.

Example:

List<Integer> integers = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);

Observable.from(integers)
    .filter(number -> {
        return (number  % 2 == 0); 
        // odd numbers will return false, that will cause them to be filtered 
    })
    .map(i -> {
        return Math.pow(i, 2); // take each number and multiply by power of 2
    }) 
    .subscribe(onNext -> {
         System.out.println(onNext); // print out the remaining numbers
    });

This code will print out

0.0
4.0
16.0
36.0
64.0


Got any rx-java Question?