RxJava - Transforming Operators



Following are the operators which are used to transform an item emitted from an Observable.

Sr.No. Operator & Description
1

buffer

Gathers items from Observable into bundles periodically and then emit the bundles rather than items.

2

flatMap

Used in nested observables. Transforms items into Observables. Then flatten the items into single Observable.

3

groupBy

Divide an Observable into set of Observables organized by key to emit different group of items.

4

map

Apply a function to each emitted item to transform it.

5

scan

Apply a function to each emitted item, sequentially and then emit the successive value.

6

window

Gathers items from Observable into Observable windows periodically and then emit the windows rather than items.

Example - Transforming Letters to Upper case using map Operator

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 .map(String::toUpperCase) .subscribe( letter -> result.append(letter)); System.out.println(result); } }

Output

Compile and Run the code to verify the following output −

ABCDEFG

Example - Flatten internal observables using flatmap Operator

ObservableTester.java

package com.tutorialspoint; import java.util.concurrent.TimeUnit; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.schedulers.Schedulers; //Using flatmap operator to flatten observables public class ObservableTester { public static void main(String[] args) throws InterruptedException { Observable<String> userIds = Observable.just("user1", "user2", "user3"); userIds.flatMap(userId -> getUserDetails(userId)) .subscribe(userDetails -> System.out.println("Received: " + userDetails)); // Keep the main thread alive to see the asynchronous results Thread.sleep(1000); } // Simulate an asynchronous network call to get user details public static Observable<String> getUserDetails(String userId) { return Observable.just("User Details of " + userId) .delay(100, TimeUnit.MILLISECONDS) .subscribeOn(Schedulers.io()); } }

Output

Compile and Run the code to verify the following output −

Received: User Details of user3
Received: User Details of user1
Received: User Details of user2
Advertisements