Creating Observable from collections

In this post under RxJava, I will explain with example how to create Observable instances from collections.

The Observable api provides methods to create Observable instance from Java Array, Collections, and Streams.

Below is an example of it

Example


1  import java.util.ArrayList;
2  import java.util.List;
3  
4  import io.reactivex.rxjava3.core.Observable;
5  
6  public class Example2 {
7      public static void main(String[] args) {
8          String[] days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
9          
10         Observable<String> observable1 = Observable.fromArray(days);
11         observable1.subscribe(s -> System.out.println(s));
12         
13         List<Integer> list = new ArrayList<Integer>(0);
14         list.add(1);
15         list.add(2);
16         list.add(3);
17         list.add(4);
18         
19         Observable<Integer> observable2 = Observable.fromIterable(list);
20         observable2.subscribe(i -> System.out.println(i));
21         
22         Observable<Integer> observable3 = Observable.fromStream(list.stream());
23         observable3.subscribe(i -> System.out.println(i));
24     }
25 }

In the above code, at line 8, I create an array named “days”.

At line 10, I create an Observable instance from array, using static method “fromArray” and passing the array “days” as arguments.

At line 13, I create a List instance named “list”

At line 19, I create an Observable instance from java collections, using static method “fromIterable” and passing the java collection “list” as arguments.

At line 22, I create an Observable instance from Java Stream using static method “fromStream”.

We subscribe to the Observables “observable1”, “observable2”, and “observable3”, by calling the “subscribe” method, and passing the callback functionality as an argument to “subscribe” method. This callback function is called whenever an item is sent from the Observable. In our example this callback function simply prints the item sent.

In this way we can create Observable instance from Java Array, Collections, and Streams.

Leave a Reply