RxJava - Creating Operators



Following are the operators which are used to create an Observable.

Sr.No. Operator & Description
1

create

Creates an Observable from scratch and allows observer method to call programmatically.

2

defer

Do not create an Observable until an observer subscribes. Creates a fresh observable for each observer.

3

empty/never/throw

Creates an Observable with limited behavior.

4

from

Converts an object/data structure into an Observable.

5

interval

Creates an Observable emitting integers in sequence with a gap of specified time interval.

6

just

Converts an object/data structure into an Observable to emit the same or same type of objects.

7

range

Creates an Observable emitting integers in sequence of given range.

8

repeat

Creates an Observable emitting integers in sequence repeatedly.

9

start

Creates an Observable to emit the return value of a function.

10

timer

Creates an Observable to emit a single item after given delay.

11

fromArray

Converts an array into an Observable.

Example - Creating Observable using Array of Items

ObservableTester.java

package com.tutorialspoint;

import io.reactivex.rxjava3.core.Observable;

//Using fromArray operator to create 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
         .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 - Creating Observable using a Single Item

ObservableTester.java

package com.tutorialspoint;

import io.reactivex.rxjava3.core.Observable;

//Using just operator to create an Observable
public class ObservableTester  {
   public static void main(String[] args) { 
      String message = "Hello World";
      Observable<String> observable = Observable.just(message);
      observable
         .map(String::toUpperCase)
         .subscribe( System.out::println);
   }
}

Output

Compile and Run the code to verify the following output −

HELLO WORLD
Advertisements