There is one common operation in stream/functional land in other languages, that's orElse(). It serves like an if, where when the current chain didn't get any result, it changes to the alternate one. In a language with Maybe types it'd basically continue the chain for a Some type or change to the orElse on a None type.
Ideal case:
Observable.just(false)
.filter(value -> { return value; })
.map(value -> { return 1; })
.orElse(Observable.just(0));
Observable.<Boolean>error(new IllegalStateException("Just playing"))
.filter(value -> { return value; })
.map(value -> { return 1; })
.orElse(Observable.just(0));
It can be currently reproduced using concat and takeFirst, but it's just not semantically the same, and doesn't cover error handling properly.
Observable.concat(Observable.just(false)
.filter(value -> { return value; })
.map(value -> { return 1; }),
Observable.just(0))
.takeFirst();
RxJava, once the hottest framework in Android development, is dying. It's dying quietly, without drawing much attention to itself. RxJava's former fans and advocates moved on to new shiny things, so there is no one left to say a proper eulogy over this, once very popular, framework.
RxJava is a Java library that enables Functional Reactive Programming in Android development. It raises the level of abstraction around threading in order to simplify the implementation of complex concurrent behavior.
RxJava Operators: Operators for Transforming Observables — You are here. RxJava Operators: Operators for Filtering Observables. RxJava Operators: Operators for Combining Observables. RxJava Operators: Utility Operators.
Single. Single is an Observable that always emit only one value or throws an error. A typical use case of Single observable would be when we make a network call in Android and receive a response. Sample Implementation: The below code always emits a Single user object.
It looks like they have that, but with different naming: defaultIfEmpty or switchIfEmpty.
Observable.just(false)
.filter(value -> value)
.map(value -> 1)
.defaultIfEmpty(0)
.subscribe(val -> {
// val == 0
});
Observable.just(false)
.filter(value -> value)
.map(value -> 1)
.switchIfEmpty(Observable.just(0))
.subscribe(val -> {
// val == 0
});
// Error thrown from the first observable
Observable.<Boolean>error(new IllegalStateException("Crash!"))
.filter(value -> value)
.map(value -> 1)
.switchIfEmpty(Observable.<Integer>error(new IllegalStateException("Boom!")))
.subscribe(val -> {
// never reached
}, error -> {
// error.getMessage() == "Crash!"
});
// Error thrown from the second observable
Observable.just(false)
.filter(value -> value)
.map(value -> 1)
.switchIfEmpty(Observable.<Integer>error(new IllegalStateException("Boom!")))
.subscribe(val -> {
// never reached
}, error -> {
// error.getMessage() == "Boom!"
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With