Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:


1. Introduction

In this tutorial, we’ll be looking at the Maybe<T> type in RxJava – which represents a stream which can emit a single value, complete in an empty state or report an error.

2. The Maybe Type

Maybe is a special kind of Observable which can only emit zero or one item, and report an error if the computation fails at some point.

In this regard, it’s like a union of Single and Completable. All these reduced types, including Maybe, offer a subset of the Flowable operators. This means we can work with Maybe like a Flowable as long as the operation makes sense for 0 or 1 items.

Since it can only emit one value, it doesn’t support backpressure handling as with a Flowable:

  .map(x -> x + 7)
  .filter(x -> x > 0)

There are onSuccess, onError and onComplete signals that can be subscribed from a Maybe source:

        x -> System.out.print("Emitted item: " + x),
        ex -> System.out.println("Error: " + ex.getMessage()),
        () -> System.out.println("Completed. No items.")

The above code will print Emitted item: 1 since this source will emit a success value.

For the same subscriptions:

  • Maybe.empty().subscribe(…) will print “Completed. No items.”
  • Maybe.error(new Exception(“error”)).subscribe(…) will print “Error: error”

These events are mutually exclusive for Maybe. That is, onComplete won’t be invoked after onSuccess. This is slightly different from Flowable since onComplete will be invoked when the stream is complete even after possibly some onNext invocations.

Single doesn’t have onComplete signal like Maybe because it’s meant to capture a reactive pattern which can either emit one item or fail.

On the other hand, Completable lacks onSuccess since it’s meant to deal with complete/fail situations only.

Another use case for the Maybe type is using it in combination with Flowable. The firstElement() method can be used to create Maybe from Flowable:

Flowable<String> visitors = ...
    v -> System.out.println("1000th visitor: " + v + " won the prize"), 
    ex -> System.out.print("Error: " + ex.getMessage()), 
    () -> System.out.print("We need more marketing"));

4. Conclusion

In this short tutorial, we quickly looked on RxJava Maybe<T> usage, and how it relates to other reactive types like Flowable, Single and Completable.

As always code samples can be found over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

res – Junit (guide) (cat=Reactive)
Comments are closed on this article!