Reactive Extensions for the JVM – a library for composing asynchronous and event-based programs using observable sequences for the Java VM.
—
Maybe is RxJava's reactive type for operations that emit zero or one item or an error. It's perfect for optional async operations like cache lookups, optional database queries, or computations that may or may not produce a result.
Factory methods for creating Maybe instances.
/**
* Creates a Maybe that emits a single item
* @param item the item to emit
* @return Maybe that emits the single item
*/
public static <T> Maybe<T> just(T item);
/**
* Creates a Maybe that completes without emitting any item
* @return Maybe that completes empty
*/
public static <T> Maybe<T> empty();
/**
* Creates a Maybe from a callable, executed lazily
* @param callable the Callable to execute, null result means empty
* @return Maybe that emits the callable result or empty if null
*/
public static <T> Maybe<T> fromCallable(Callable<? extends T> callable);
/**
* Creates a Maybe using a custom emitter function
* @param source the MaybeOnSubscribe function
* @return Maybe created from the custom emitter
*/
public static <T> Maybe<T> create(MaybeOnSubscribe<T> source);
/**
* Creates a Maybe that only calls onError
* @param error the error to emit
* @return Maybe that emits the error
*/
public static <T> Maybe<T> error(Throwable error);
/**
* Creates a Maybe that defers creation until subscription
* @param maybeSupplier supplier of Maybe to defer
* @return Maybe that defers to supplied Maybe
*/
public static <T> Maybe<T> defer(Supplier<? extends MaybeSource<? extends T>> maybeSupplier);
/**
* Creates a Maybe from an Optional, empty if Optional is empty
* @param optional the Optional to convert
* @return Maybe that emits Optional value or empty
*/
public static <T> Maybe<T> fromOptional(Optional<T> optional);
/**
* Creates a Maybe from a Single source
* @param source the SingleSource to convert
* @return Maybe that emits the Single result
*/
public static <T> Maybe<T> fromSingle(SingleSource<T> source);Transform the emitted item or chain with other reactive types.
/**
* Transform the item using a mapping function (if present)
* @param mapper function to transform the item
* @return Maybe with transformed item or empty
*/
public final <R> Maybe<R> map(Function<? super T, ? extends R> mapper);
/**
* Transform the item to another Maybe and flatten the result
* @param mapper function returning Maybe for the item
* @return Maybe from the flattened result
*/
public final <R> Maybe<R> flatMap(Function<? super T, ? extends MaybeSource<? extends R>> mapper);
/**
* Transform the item to a Single
* @param mapper function returning Single for the item
* @return Single from the mapped result or error if empty
*/
public final <R> Single<R> flatMapSingle(Function<? super T, ? extends SingleSource<? extends R>> mapper);
/**
* Transform the item to an Observable
* @param mapper function returning ObservableSource for the item
* @return Observable from the mapped result or empty Observable
*/
public final <R> Observable<R> flatMapObservable(Function<? super T, ? extends ObservableSource<? extends R>> mapper);
/**
* Transform the item to a Flowable
* @param mapper function returning Publisher for the item
* @return Flowable from the mapped result or empty Flowable
*/
public final <R> Flowable<R> flatMapPublisher(Function<? super T, ? extends Publisher<? extends R>> mapper);
/**
* Transform empty completion to another Maybe
* @param other Maybe to emit if this Maybe is empty
* @return Maybe that emits this item or other if empty
*/
public final Maybe<T> switchIfEmpty(MaybeSource<? extends T> other);
/**
* Cast the emitted item to a different type (if present)
* @param clazz the target class to cast to
* @return Maybe with cast item or empty
*/
public final <U> Maybe<U> cast(Class<U> clazz);
/**
* Filter the item using a predicate (empty if predicate fails)
* @param predicate function to test the item
* @return Maybe with item if predicate passes, empty otherwise
*/
public final Maybe<T> filter(Predicate<? super T> predicate);Provide fallback behavior when Maybe is empty.
/**
* Return a default item if this Maybe is empty
* @param defaultItem the item to emit if empty
* @return Maybe that emits the item or defaultItem if empty
*/
public final Single<T> defaultIfEmpty(T defaultItem);
/**
* Switch to another Maybe if this Maybe is empty
* @param other Maybe to switch to if empty
* @return Maybe that emits this item or switches to other if empty
*/
public final Maybe<T> switchIfEmpty(MaybeSource<? extends T> other);
/**
* Convert to Single with default value if empty
* @param defaultItem the item to emit if empty
* @return Single that emits the item or defaultItem
*/
public final Single<T> toSingle(T defaultItem);Control subscription behavior and execution context.
/**
* Subscribe with a simple onSuccess callback
* @param onSuccess function called when item is emitted
* @return Disposable for managing the subscription
*/
public final Disposable subscribe(Consumer<? super T> onSuccess);
/**
* Subscribe with onSuccess and onError callbacks
* @param onSuccess function called when item is emitted
* @param onError function called on error
* @return Disposable for managing the subscription
*/
public final Disposable subscribe(Consumer<? super T> onSuccess, Consumer<? super Throwable> onError);
/**
* Subscribe with onSuccess, onError and onComplete callbacks
* @param onSuccess function called when item is emitted
* @param onError function called on error
* @param onComplete action called on empty completion
* @return Disposable for managing the subscription
*/
public final Disposable subscribe(Consumer<? super T> onSuccess, Consumer<? super Throwable> onError, Action onComplete);
/**
* Subscribe with full MaybeObserver interface
* @param observer the MaybeObserver to receive emissions
*/
public final void subscribe(MaybeObserver<? super T> observer);
/**
* Subscribe and block until completion, returning optional result
* @return Optional containing the item or empty
*/
public final Optional<T> blockingGet();
/**
* Specify the Scheduler for subscription operations
* @param scheduler the Scheduler to use for subscriptions
* @return Maybe operating on the specified scheduler
*/
public final Maybe<T> subscribeOn(Scheduler scheduler);
/**
* Specify the Scheduler for observation operations
* @param scheduler the Scheduler to use for observations
* @return Maybe observing on the specified scheduler
*/
public final Maybe<T> observeOn(Scheduler scheduler);
/**
* Add a delay before emitting the item or completing empty
* @param delay the delay duration
* @param unit the time unit
* @return Maybe that emits/completes after the delay
*/
public final Maybe<T> delay(long delay, TimeUnit unit);Handle errors in the Maybe stream.
/**
* Return a default item when an error occurs
* @param defaultItem the item to emit on error
* @return Maybe that emits defaultItem on error
*/
public final Maybe<T> onErrorReturn(T defaultItem);
/**
* Return a default item using a function when an error occurs
* @param resumeFunction function to generate default item from error
* @return Maybe that emits result of resumeFunction on error
*/
public final Maybe<T> onErrorReturn(Function<? super Throwable, ? extends T> resumeFunction);
/**
* Resume with another Maybe when an error occurs
* @param resumeSource Maybe to switch to on error
* @return Maybe that switches to resumeSource on error
*/
public final Maybe<T> onErrorResumeNext(MaybeSource<? extends T> resumeSource);
/**
* Complete empty instead of error when an error occurs
* @param predicate function to test if error should be converted to empty
* @return Maybe that completes empty for matching errors
*/
public final Maybe<T> onErrorComplete(Predicate<? super Throwable> predicate);
/**
* Retry the subscription when an error occurs
* @param times maximum number of retry attempts
* @return Maybe that retries up to the specified times
*/
public final Maybe<T> retry(long times);
/**
* Perform side-effect action when an error occurs
* @param onError action to perform on error
* @return Maybe that performs the action on error
*/
public final Maybe<T> doOnError(Consumer<? super Throwable> onError);Perform side-effect actions without modifying the stream.
/**
* Perform an action when an item is emitted
* @param onSuccess action to perform when item is emitted
* @return Maybe that performs the action on success
*/
public final Maybe<T> doOnSuccess(Consumer<? super T> onSuccess);
/**
* Perform an action when Maybe completes empty
* @param onComplete action to perform on empty completion
* @return Maybe that performs the action on empty completion
*/
public final Maybe<T> doOnComplete(Action onComplete);
/**
* Perform an action when subscription occurs
* @param onSubscribe action to perform on subscription
* @return Maybe that performs the action on subscription
*/
public final Maybe<T> doOnSubscribe(Consumer<? super Disposable> onSubscribe);
/**
* Perform an action when disposal occurs
* @param onDispose action to perform on disposal
* @return Maybe that performs the action on disposal
*/
public final Maybe<T> doOnDispose(Action onDispose);
/**
* Perform an action on any terminal event (success, error, complete)
* @param onEvent action to perform on terminal event
* @return Maybe that performs the action on terminal events
*/
public final Maybe<T> doFinally(Action onEvent);Convert to other reactive types.
/**
* Convert to Observable (emits item or completes empty)
* @return Observable that emits the Maybe item or completes empty
*/
public final Observable<T> toObservable();
/**
* Convert to Flowable (emits item or completes empty)
* @return Flowable that emits the Maybe item or completes empty
*/
public final Flowable<T> toFlowable();
/**
* Convert to Single (errors if empty)
* @return Single that emits the Maybe item or errors if empty
*/
public final Single<T> toSingle();
/**
* Convert to Completable (ignores the item)
* @return Completable that signals completion or error
*/
public final Completable ignoreElement();/**
* Interface for creating custom Maybe sources
*/
public interface MaybeOnSubscribe<T> {
void subscribe(MaybeEmitter<T> emitter) throws Throwable;
}
/**
* Emitter interface for custom Maybe creation
*/
public interface MaybeEmitter<T> {
void onSuccess(T value);
void onError(Throwable error);
void onComplete();
boolean isDisposed();
}
/**
* Observer interface for Maybe
*/
public interface MaybeObserver<T> {
void onSubscribe(Disposable d);
void onSuccess(T t);
void onError(Throwable e);
void onComplete();
}
/**
* Base interface for Maybe sources
*/
public interface MaybeSource<T> {
void subscribe(MaybeObserver<? super T> observer);
}Usage Examples:
import io.reactivex.rxjava3.core.Maybe;
import io.reactivex.rxjava3.schedulers.Schedulers;
import java.util.Optional;
// Basic Maybe operations
Maybe.just("Hello")
.subscribe(
item -> System.out.println("Got: " + item),
error -> System.err.println("Error: " + error),
() -> System.out.println("Empty")
);
// Maybe from Optional
Optional<String> optional = Optional.of("Value");
Maybe.fromOptional(optional)
.subscribe(System.out::println);
// Empty Maybe
Maybe.<String>empty()
.defaultIfEmpty("Default")
.subscribe(System.out::println);
// Conditional emission
Maybe.fromCallable(() -> {
return Math.random() > 0.5 ? "Lucky!" : null;
})
.subscribe(
item -> System.out.println("Got: " + item),
error -> System.err.println("Error: " + error),
() -> System.out.println("Empty result")
);
// Chaining with flatMap
Maybe.just("user123")
.flatMap(userId -> {
// Simulate database lookup that might return empty
return Math.random() > 0.3 ?
Maybe.just("User: " + userId) :
Maybe.empty();
})
.switchIfEmpty(Maybe.just("Default User"))
.subscribe(System.out::println);
// Error handling with fallback
Maybe.fromCallable(() -> {
if (Math.random() > 0.7) {
throw new RuntimeException("Random failure");
}
return "Success";
})
.onErrorReturn("Fallback value")
.subscribe(System.out::println);
// Converting between types
Maybe.just(42)
.filter(x -> x > 50) // Will be empty since 42 > 50 is false
.toSingle(-1) // Convert to Single with default
.subscribe(System.out::println);Install with Tessl CLI
npx tessl i tessl/maven-io-reactivex-rxjava3--rxjava