Skip to content

RxJava fromCallable operator

  • by
RxJava fromCallable operator

1. Overview

In this article, we will discuss the RxJava fromCallable operator with a few examples.

2. Callable

A Runnable is a core interface and the implementing classes execute in threads. The Callable is like Runnable declared in the java.util.concurrent package and runs on the threads from the thread pool such as ExecutorService.

A Runnable, however, does not return a result and cannot throw a checked exception whereas Callable interface contains a single, no-argument call() method that returns a result or throws Exception if unable to compute the result. See this article for more details on Runnable and Callable.

2. RxJava from operator

The RxJava from operator constructs a sequence from a pre-existing source or generator type. The from is like Just, but note that From will dive into an array or an iterable or something of that sort to pull out items to emit, while Just will simply emit the array or iterable or what-have-you as it is, unchanged, as a single item.

See Just operator.

The fromCallable is a static method and variant of this from operator that accepts the callable sources as input.

It uses the postfix naming convention (i.e., the method name contains the argument type). Here, Iterable is the argument type and the method name fromCallable contains Iterable to avoid overload resolution ambiguities.

3. RxJava fromCallable operator

When a consumer subscribes, it invokes the provided java.util.concurrent.Callable and relays its return value (or thrown exception) to that consumer.

public static <T> Observable<T> fromCallable(@NonNull Callable<? extends T> callable)

It can create all RxJava flow types such Flowable, Single, MayBe, Completable and Observable. Single and Completable are new types that represent reduced types of Observable and have a more concise API.

3.1. RxJava fromCallable example

@Test
    public void testFromCallable() {
        Callable<String> callable = new Callable<String>() {
            @Override
            public String call() throws Exception {
                System.out.println("Callable execution:" + "Hello World!");
                return "Hello World!";
            }
        };

        Observable<String> observable = Observable.fromCallable(callable);

        observable.subscribe(item -> System.out.println("result in consumer:" + item), error -> error.printStackTrace(),
                () -> System.out.println("Done"));
    }

If you execute the above test case, it prints the following result in the console. As you can see, the Observable invokes the callable and emits the result of the callable to the observer\consumer.

Callable execution:Hello World!
result in consumer:Hello World!
Done

3.2. Flowable fromCallable example

Observable sources don’t support backpressure. The RxJava 2 represents the backpressure aware sources by using the Flowable.

Backpressure is when your observable (publisher) is creating more events than your subscriber can handle. So your subscribers could miss events or have a huge queue of events which just leads to out of memory, eventually. 

Similar to Observable, you can create a Flowable using the fromCallable operator.

@Test
    public void testFlowableFromCallable() {
        Callable<String> callable = new Callable<String>() {
            @Override
            public String call() throws Exception {
                System.out.println("Callable execution:" + "Hello World!");
                return "Hello World!";
            }
        };

        Flowable<String> flowable = Flowable.fromCallable(callable);

        flowable.subscribe(item -> System.out.println("result in consumer:" + item), error -> error.printStackTrace(),
                () -> System.out.println("Done"));
    }

3.3. Completable fromCallable example

Completable represent Observable that emits no value, but only terminal events, either onError or onCompleted.

So here the Completable ignores the actual returned value and the Completable simply completes.

 @Test
    public void testCompletableFromCallable() {
        Callable<String> callable = new Callable<String>() {
            @Override
            public String call() throws Exception {
                System.out.println("Callable execution:" + "Hello World!");
                return "Hello World!";
            }
        };

        Completable completable = Completable.fromCallable(callable);

        completable.subscribe(() -> System.out.println("Done"),
                error -> error.printStackTrace());
    }

The completable does not have onNext for the consumer as they emit no elements. So executing the above code produces the following result.

Callable execution:Hello World!
Done

4. Conclusion

To sum up, we have learned the RxJava fromCallable operator with examples. You can find code samples in our GitHub repository.

Leave a Reply

Your email address will not be published. Required fields are marked *