RxJava: Reactive Extensions for the JVM – a library for composing asynchronous and event-based programs using observable sequences for the Java VM.
—
Reactive type that only signals completion or error without emitting items. Completable is ideal for fire-and-forget operations, side effects, and operations where you only care about successful completion rather than return values.
Factory methods for creating Completable instances.
/**
* Creates a Completable that immediately completes
*/
public static Completable complete();
/**
* Creates a Completable from an Action
*/
public static Completable fromAction(Action action);
/**
* Creates a Completable from a Runnable
*/
public static Completable fromRunnable(Runnable runnable);
/**
* Creates a Completable from a Callable (ignoring the return value)
*/
public static Completable fromCallable(Callable<?> callable);
/**
* Creates a Completable from a Future (ignoring the result)
*/
public static Completable fromFuture(Future<?> future);
/**
* Creates a Completable using the provided CompletableOnSubscribe function
*/
public static Completable create(CompletableOnSubscribe source);
/**
* Creates a Completable that completes after a delay
*/
public static Completable timer(long delay, TimeUnit unit);
public static Completable timer(long delay, TimeUnit unit, Scheduler scheduler);
/**
* Creates a Completable that only calls onError
*/
public static Completable error(Throwable error);
public static Completable error(Callable<? extends Throwable> errorSupplier);
/**
* Creates a Completable that never completes or errors
*/
public static Completable never();
/**
* Defers Completable creation until subscription
*/
public static Completable defer(Callable<? extends CompletableSource> completableSupplier);
/**
* Creates a Completable from other reactive types (ignoring their values)
*/
public static Completable fromObservable(ObservableSource<?> observable);
public static Completable fromFlowable(Publisher<?> flowable);
public static Completable fromSingle(SingleSource<?> single);
public static Completable fromMaybe(MaybeSource<?> maybe);Chain Completables and transform them into other reactive types.
/**
* Chains this Completable with another reactive type
*/
public final <T> Observable<T> andThen(ObservableSource<T> next);
public final <T> Flowable<T> andThen(Publisher<T> next);
public final <T> Single<T> andThen(SingleSource<T> next);
public final <T> Maybe<T> andThen(MaybeSource<T> next);
public final Completable andThen(CompletableSource next);
/**
* Transforms this Completable using a transformer
*/
public final <R> R as(CompletableConverter<? extends R> converter);
public final <R> R to(CompletableConverter<? extends R> converter);
public final Completable compose(CompletableTransformer transformer);Combine multiple Completables.
/**
* Merges multiple Completables (completes when all complete)
*/
public static Completable merge(CompletableSource... sources);
public static Completable merge(Iterable<? extends CompletableSource> sources);
public static Completable merge(Publisher<? extends CompletableSource> sources);
/**
* Merges with concurrency limit
*/
public static Completable merge(Publisher<? extends CompletableSource> sources, int maxConcurrency);
/**
* Concatenates Completables sequentially
*/
public static Completable concat(CompletableSource... sources);
public static Completable concat(Iterable<? extends CompletableSource> sources);
public static Completable concat(Publisher<? extends CompletableSource> sources);
/**
* Returns the first Completable to complete
*/
public static Completable amb(CompletableSource... sources);
public static Completable amb(Iterable<? extends CompletableSource> sources);
/**
* Concatenates this Completable with others
*/
public final Completable concatWith(CompletableSource other);
/**
* Merges this Completable with others
*/
public final Completable mergeWith(CompletableSource other);Handle errors in Completable operations.
/**
* Resumes with another Completable if an error occurs
*/
public final Completable onErrorResumeNext(Function<? super Throwable, ? extends CompletableSource> errorMapper);
public final Completable onErrorResumeNext(CompletableSource resumeCompletableSource);
/**
* Converts errors to completion
*/
public final Completable onErrorComplete();
public final Completable onErrorComplete(Predicate<? super Throwable> predicate);
/**
* Retry on error
*/
public final Completable retry();
public final Completable retry(long times);
public final Completable retry(BiPredicate<? super Integer, ? super Throwable> predicate);
public final Completable retryWhen(Function<? super Flowable<Throwable>, ? extends Publisher<?>> handler);Control execution context for Completables.
/**
* Specifies the Scheduler on which the Completable will operate
*/
public final Completable subscribeOn(Scheduler scheduler);
/**
* Specifies the Scheduler on which observers will be notified
*/
public final Completable observeOn(Scheduler scheduler);Add delays and timeouts to Completables.
/**
* Delays the completion signal
*/
public final Completable delay(long delay, TimeUnit unit);
public final Completable delay(long delay, TimeUnit unit, Scheduler scheduler);
/**
* Adds a timeout to the Completable
*/
public final Completable timeout(long timeout, TimeUnit unit);
public final Completable timeout(long timeout, TimeUnit unit, Scheduler scheduler);
public final Completable timeout(long timeout, TimeUnit unit, CompletableSource other);Repeat Completable operations.
/**
* Repeats the Completable subscription indefinitely
*/
public final Completable repeat();
/**
* Repeats the Completable subscription a specified number of times
*/
public final Completable repeat(long times);
/**
* Repeats the Completable based on a condition
*/
public final Completable repeatWhen(Function<? super Flowable<Object>, ? extends Publisher<?>> handler);
/**
* Repeats until a condition becomes true
*/
public final Completable repeatUntil(BooleanSupplier stop);Convert Completable to other reactive types.
/**
* Converts Completable to Observable that emits no items but completes
*/
public final <T> Observable<T> toObservable();
/**
* Converts Completable to Flowable that emits no items but completes
*/
public final <T> Flowable<T> toFlowable();
/**
* Converts Completable to Single that emits the provided value on completion
*/
public final <T> Single<T> toSingle(Callable<? extends T> completionValueSupplier);
/**
* Converts Completable to Maybe that completes empty
*/
public final <T> Maybe<T> toMaybe();
/**
* Converts Completable to Single that emits the provided value
*/
public final <T> Single<T> toSingleDefault(T completionValue);Subscribe to a Completable and handle completion.
/**
* Subscribes with separate callbacks
*/
public final Disposable subscribe();
public final Disposable subscribe(Action onComplete);
public final Disposable subscribe(Action onComplete, Consumer<? super Throwable> onError);
/**
* Subscribes with a CompletableObserver
*/
public final void subscribe(CompletableObserver observer);
/**
* Blocking operations - use with caution
*/
public final void blockingAwait();
public final boolean blockingAwait(long timeout, TimeUnit unit);Additional utility operations for Completables.
/**
* Caches the result of the Completable
*/
public final Completable cache();
/**
* Performs side-effects without affecting the Completable
*/
public final Completable doOnComplete(Action onComplete);
public final Completable doOnError(Consumer<? super Throwable> onError);
public final Completable doOnSubscribe(Consumer<? super Disposable> onSubscribe);
public final Completable doOnDispose(Action onDispose);
public final Completable doFinally(Action onFinally);
/**
* Hides the identity of the Completable
*/
public final Completable hide();
/**
* Lifts a CompletableOperator
*/
public final Completable lift(CompletableOperator lift);
/**
* Materializes onComplete and onError events as notifications
*/
public final Single<Notification<Void>> materialize();Basic Completable Operations:
import io.reactivex.Completable;
import io.reactivex.CompletableObserver;
import io.reactivex.disposables.Disposable;
// Simple completion operation
Completable saveData = Completable.fromAction(() -> {
// Simulate saving data
System.out.println("Saving data...");
Thread.sleep(1000);
System.out.println("Data saved!");
});
saveData.subscribe(new CompletableObserver() {
@Override
public void onSubscribe(Disposable d) {
System.out.println("Started save operation");
}
@Override
public void onComplete() {
System.out.println("Save completed successfully");
}
@Override
public void onError(Throwable e) {
System.err.println("Save failed: " + e.getMessage());
}
});
// Lambda-style subscription
saveData.subscribe(
() -> System.out.println("Success!"),
error -> error.printStackTrace()
);Sequential Operations with andThen:
Completable setup = Completable.fromAction(() -> System.out.println("Setting up..."));
Completable process = Completable.fromAction(() -> System.out.println("Processing..."));
Completable cleanup = Completable.fromAction(() -> System.out.println("Cleaning up..."));
// Chain operations sequentially
setup.andThen(process)
.andThen(cleanup)
.subscribe(
() -> System.out.println("All operations completed"),
error -> System.err.println("Operation failed: " + error)
);
// Chain with other reactive types
Single<String> result = setup
.andThen(Single.just("Operation result"));
result.subscribe(value -> System.out.println("Result: " + value));Parallel Operations with merge:
Completable task1 = Completable.fromAction(() -> {
System.out.println("Task 1 starting");
Thread.sleep(1000);
System.out.println("Task 1 completed");
}).subscribeOn(Schedulers.io());
Completable task2 = Completable.fromAction(() -> {
System.out.println("Task 2 starting");
Thread.sleep(1500);
System.out.println("Task 2 completed");
}).subscribeOn(Schedulers.io());
Completable task3 = Completable.fromAction(() -> {
System.out.println("Task 3 starting");
Thread.sleep(800);
System.out.println("Task 3 completed");
}).subscribeOn(Schedulers.io());
// All tasks run in parallel, complete when all finish
Completable.merge(Arrays.asList(task1, task2, task3))
.subscribe(
() -> System.out.println("All tasks completed"),
error -> System.err.println("One or more tasks failed")
);Error Handling and Retry:
Completable unreliableOperation = Completable.fromAction(() -> {
if (Math.random() > 0.7) {
throw new RuntimeException("Random failure");
}
System.out.println("Operation succeeded");
});
// Retry with backoff
unreliableOperation
.retry(3)
.subscribe(
() -> System.out.println("Operation completed successfully"),
error -> System.err.println("Operation failed after retries: " + error)
);
// Convert error to completion
unreliableOperation
.onErrorComplete()
.subscribe(() -> System.out.println("Completed (success or error ignored)"));Delayed and Timer Operations:
// Delay before completion
Completable delayedTask = Completable.fromAction(() -> System.out.println("Task executed"))
.delay(2, TimeUnit.SECONDS);
delayedTask.subscribe(() -> System.out.println("Delayed task completed"));
// Timer that just completes after delay
Completable.timer(1, TimeUnit.SECONDS)
.subscribe(() -> System.out.println("Timer completed"));
// Timeout handling
Completable longRunningTask = Completable.fromAction(() -> {
Thread.sleep(5000); // 5 seconds
System.out.println("Long task completed");
});
longRunningTask
.timeout(2, TimeUnit.SECONDS)
.subscribe(
() -> System.out.println("Task completed in time"),
error -> System.err.println("Task timed out: " + error)
);Repetition and Loops:
// Repeat operation 3 times
Completable heartbeat = Completable.fromAction(() -> {
System.out.println("Heartbeat: " + System.currentTimeMillis());
});
heartbeat.repeat(3)
.subscribe(
() -> System.out.println("All heartbeats sent"),
error -> error.printStackTrace()
);
// Repeat with condition
AtomicInteger counter = new AtomicInteger(0);
Completable increment = Completable.fromAction(() -> {
int current = counter.incrementAndGet();
System.out.println("Counter: " + current);
});
increment.repeatUntil(() -> counter.get() >= 5)
.subscribe(() -> System.out.println("Counter reached limit"));Converting to Other Types:
Completable operation = Completable.fromAction(() -> System.out.println("Operation done"));
// Convert to Single with result value
Single<String> result = operation.toSingleDefault("Success");
result.subscribe(value -> System.out.println("Result: " + value));
// Convert to Observable that emits no items
Observable<Void> observable = operation.toObservable();
observable.subscribe(
item -> System.out.println("Item: " + item), // Never called
error -> error.printStackTrace(),
() -> System.out.println("Observable completed")
);
// Chain with Single
Single<Integer> calculation = operation.andThen(Single.just(42));
calculation.subscribe(value -> System.out.println("Calculated: " + value));/**
* Observer interface for Completables
*/
public interface CompletableObserver {
void onSubscribe(Disposable d);
void onComplete();
void onError(Throwable e);
}
/**
* Functional interface for creating Completables
*/
public interface CompletableOnSubscribe {
void subscribe(CompletableEmitter emitter) throws Exception;
}
/**
* Emitter for CompletableOnSubscribe
*/
public interface CompletableEmitter {
void onComplete();
void onError(Throwable t);
void setDisposable(Disposable d);
void setCancellable(Cancellable c);
boolean isDisposed();
}
/**
* Base interface for Completable sources
*/
public interface CompletableSource {
void subscribe(CompletableObserver observer);
}
/**
* Transformer interface for Completables
*/
public interface CompletableTransformer {
CompletableSource apply(Completable upstream);
}
/**
* Converter interface for Completables
*/
public interface CompletableConverter<R> {
R apply(Completable upstream);
}Install with Tessl CLI
npx tessl i tessl/maven-io-reactivex-rxjava2--rxjava