RxJava - Filtering Operators



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.

Example - Taking First two items

ObservableTester.java

package com.tutorialspoint;

import io.reactivex.rxjava3.core.Observable;

// Using take operator to filter items
public class ObservableTester  {
   public static void main(String[] args) { 
      String[] letters = {"a", "b", "c", "d", "e", "f", "g"};
      final StringBuilder result = new StringBuilder();
      Observable<String> observable = Observable.fromArray(letters);
      observable
         .take(2)
         .subscribe( letter -> result.append(letter));
      System.out.println(result);
   }
}

Output

Compile and Run the code to verify the following output −

ab

Example - Skipping First two items

ObservableTester.java

package com.tutorialspoint;

import io.reactivex.rxjava3.core.Observable;

//Using map operator to tranform an item emitted
public class ObservableTester  {
   public static void main(String[] args) { 
      String[] letters = {"a", "b", "c", "d", "e", "f", "g"};
      final StringBuilder result = new StringBuilder();
      Observable<String> observable = Observable.fromArray(letters);
      observable
         .skip(2)
         .subscribe( letter -> result.append(letter));
      System.out.println(result);
   }
}

Output

Compile and Run the code to verify the following output −

cdefg
Advertisements