RxJava - Transforming Operators

RxJava - Transforming Operators

Transforming operators are used when we want to model the data coming from a sequence to match with our requirements

RxJava has different operators to perform action on emited data.

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.

 

Examples

Map:

public class RxOperators {
 
    public static void main(String args[])
    {
        Observable.just(2,3,4)
                .map(s->s*s)
                .subscribe(s->System.out.println(s))
                .dispose();
       
    }
}

output

4
9
16

 

FlatMap 

final List<String> race = new ArrayList<>(Arrays.asList("sunday", "monday", "tuesday", "wednesday", "thurday", "friday","saterday"));

        Observable.fromArray(race)
                .flatMap(new Function<List<String>, ObservableSource<? >>() {

             @Override
             public ObservableSource<? > apply(List<String> t) throws Exception {
                final int delay = new Random().nextInt(5);
                        return Observable.just(t).map(s->s.toString().toUpperCase())
                                .delay(delay, TimeUnit.SECONDS);
                 
             }
         }).subscribe(System.out::println);

        Thread.sleep(5000);

 

Output

[SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURDAY, FRIDAY, SATERDAY]