RxJava2带条件操作的调用链式优化方案咨询
Elegant RxJava2 Chained Implementation for Conditional Second Call
Hey there! Nice question—RxJava2 has a few clean, idiomatic ways to handle this "run first call, then run second only if first returns false" logic. Let me break down the most straightforward approaches:
1. Use flatMap for Explicit Branching
This is the most readable approach, especially if you need to handle different return types or add extra logic in each branch.
// Assume firstCall() returns Observable<Boolean> // Assume secondCall() returns Observable<Boolean> (adjust if it's Completable/Single) firstCall() .flatMap(firstResult -> { if (firstResult) { // First call succeeded (returned true) — emit the result and end the chain return Observable.just(firstResult); } else { // First call failed (returned false) — execute the second call return secondCall(); } }) .subscribe( finalResult -> { // Handle the final result (either firstCall's true or secondCall's output) }, throwable -> { // Handle errors from either firstCall or secondCall } );
If your secondCall() is a Completable (no return value) and you just need to execute it without emitting a new value, adjust the flatMap block like this:
firstCall() .flatMap(firstResult -> { if (!firstResult) { // Run secondCall, then emit the original false result return secondCall().andThen(Observable.just(firstResult)); } return Observable.just(firstResult); }) .subscribe(...);
2. Use filter + switchIfEmpty for Concise Logic
If your use case is simple ("keep the first true result, run second call if first is false"), this one-liner style is super clean:
firstCall() // Filter out the false result — turns the Observable empty if first call returns false .filter(Boolean::booleanValue) // If the Observable is empty (i.e., first call was false), run the second call .switchIfEmpty(secondCall()) .subscribe(finalResult -> { // Will get firstCall's true, or secondCall's output }, throwable -> { // Errors from either call are caught here });
Notes to Keep in Mind
- Both approaches ensure the second call is only executed if and only if the first returns false.
- Error handling is unified: any error from either call will propagate to the
subscribeerror handler. - If you're using
Singleinstead ofObservable, replaceObservable.just()withSingle.just()and adjust operators accordingly (e.g.,switchIfEmptyworks withSingletoo).
内容的提问来源于stack exchange,提问作者Kristy Welsh
相关产品推荐
相关产品推荐

