RxJava - Utility Operators



Following are the operators which are often useful with Observables.

Sr.No. Operator & Description
1

delay

Register action to handle Observable life-cycle events.

2

materialize/dematerialize

Represents item emitted and notification sent.

3

observeOn

Specify the scheduler to be observed.

4

serialize

Force Observable to make serialized calls.

5

subscribe

Operate upon the emissions of items and notifications like complete from an Observable

6

subscribeOn

Specify the scheduler to be used by an Observable when it is subscribed to.

7

timeInterval

Convert an Observable to emit indications of the amount of time elapsed between emissions.

8

timeout

Issues error notification if specified time occurs without emitting any item.

9

timestamp

Attach timestamp to each item emitted.

9

using

Creates a disposable resource or same lifespan as that of Observable.

Example - Usage of subscribe operator

ObservableTester.java

package com.tutorialspoint; import io.reactivex.rxjava3.core.Observable; //Using subscribe operator to subscribe to an Observable 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.subscribe( letter -> result.append(letter)); System.out.println(result); } }

Output

Compile and Run the code to verify the following output −

abcdefg

Example - Usage of timestamp operator

package com.tutorialspoint; import io.reactivex.rxjava3.core.Observable; //Using subscribe operator to subscribe to an Observable 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 .timestamp() .subscribe( letter -> result.append(letter + "\n")); System.out.println(result); } }

Output

Compile and Run the code to verify the following output −

Timed[time=1758342979382, unit=MILLISECONDS, value=a]
Timed[time=1758342979386, unit=MILLISECONDS, value=b]
Timed[time=1758342979386, unit=MILLISECONDS, value=c]
Timed[time=1758342979386, unit=MILLISECONDS, value=d]
Timed[time=1758342979386, unit=MILLISECONDS, value=e]
Timed[time=1758342979386, unit=MILLISECONDS, value=f]
Timed[time=1758342979386, unit=MILLISECONDS, value=g]
Advertisements