Speacial Observables: Single, Maybe and Completable

October 12, 2018

There are a few special Observables available in RxJava: Single, Maybe and Completable.

Single

Single is an Observable that will emit only one item: it consolidates onNext() and onComplete() into a single event, so on subscribing to a Single, we can provide a Lambda for the onSuccess() and to the optional onError():

import io.reactivex.Single;

public class Main {
    public static void main(String[] args) {
        Single<String> single = Single.just("Hello Single");

        single.subscribe(System.out::println);
    }
}

Maybe

If there are 0 or 1 emissions, then we can use Maybe. To create a Maybe which will not emit an item, Maybe.empty() can be used:

import io.reactivex.Maybe;

public class Main {
    public static void main(String[] args) {
        Maybe<String> maybe = Maybe.just("Hello Maybe");

        Maybe<String> empty = Maybe.empty();

        maybe.subscribe(s -> System.out.println("Observer 1 received: " + s));

        empty.subscribe(
                s -> System.out.println("Observer 2 received: " + s),   //onSuccess()
                Throwable::printStackTrace,                             //onError()
                () -> System.out.println("Observer 2 finished!")        //onComplete()
        );
    }
}

Completable

When you need a certain action to be completed, but you don’t need any emissions, you can use Completable. You can create a Completable from various sources via methods such as fromObservable(), fromMaybe(), fromRunnable() or fromFuture():

import io.reactivex.Completable;

public class Main {
    public static void main(String[] args) {
        Completable completable = Completable.fromRunnable(() -> runProcess());

        completable.subscribe(
                () -> System.out.println("Callable finished!"), //onComplete()
                Throwable::printStackTrace                      //onError()
        );
    }

    private static void runProcess(){
        System.out.println("Process running!");
    }
}

 

András Döbröntey

About the Author

András Döbröntey

Leave a Comment:

Bitnami