How to create an RxJava 2 Observable from a Java List

As a brief note, here’s an example that shows how to create an RxJava 2 Observable from a Java List:

import io.reactivex.Observable;
import java.util.*;

/**
 * Demonstrates how to create an Observable from a List.
 * 
 * Prints:
 *    Hello
 *    world
 * 
 * See https://github.com/ReactiveX/RxJava/wiki/Creating-Observables
 * for more information.
 * 
 */
public class HelloWorld3UsingList {

    public static void main(String[] args) {

        List<String> strings = new ArrayList<String>(
            Arrays.asList("Hello", "world")
        );

        Observable<String> observable = Observable.fromIterable(strings);
        observable.subscribe(s -> System.out.println(s));

    }

}

I’ve written about RxJava before so I won’t add any more details than that, but for more RxJava examples you can search this site, or see the Github URL shown in the comments for more information.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.