RxJava - Filtering Operators

RxJava - Filtering Operators

Filter operator filters an Observable making sure that emitted items match specified condition.

Following are the operators which are used to selectively emit item(s) from an Observable.

Sr.No. Operator & Description
1

Debounce

Emits items only when timeout occurs without emiting another item.

2

Distinct

Emits only unique items.

3

ElementAt

emit only item at n index emitted by an Observable.

4

Filter

Emits only those items which pass the given predicate function.

5

First

Emits the first item or first item which passed the given criteria.

6

IgnoreElements

Do not emits any items from Observable but marks completion.

7

Last

Emits the last element from Observable.

8

Sample

Emits the most recent item with given time interval.

9

Skip

Skips the first n items from an Observable.

10

SkipLast

Skips the last n items from an Observable.

11

Take

takes the first n items from an Observable.

12

TakeLast

takes the last n items from an Observable.

 

Examples:

public class RxFiltering {
    public static void main(String args[])
    {
        Observable<Integer> sourceObservable = Observable.range(1, 10);
        

        Observable<Integer> filteredObservable = sourceObservable
          .filter(i -> i % 2 != 0);

        filteredObservable.subscribe(s->System.out.println(s
      ));
    }
}

Output

1

3

5

7

9

 

Example 2:

 Observable<Integer> sourceObservable = Observable.range(1, 10);
          Observable<Integer> takeObservable = sourceObservable
          .take(2);

            takeObservable.subscribe(s->System.out.println(s
          ));

Output

1

2

 

Example 3:

 Observable<Integer> sourceObservable = Observable.range(1, 10);
             Observable<Integer> takeWhileObservable = sourceObservable
          .takeWhile(i -> i < 5 );

            takeWhileObservable.subscribe(s->System.out.println(s
          ));

Output

1

2

3

4

 

Example 4:

Observable<Integer> sourceObservable = Observable.range(1, 10);
        Maybe<Integer> filteredObservable = sourceObservable.elementAt(4);
 
                    filteredObservable.subscribe(s->System.out.println(s));

 

Output

5