I want to "throw" custom error if an Observable
does not emit exactly one value before completing.
Let me try to show an example:
Observable<SomeClass> stream = ...
stream
.filter(...)
.singleOrError(new MyCustomException())
So I have a stream of SomeClass objects. I want to emit custom error if fitler()
does not emit exactly one element.
Since .singleOrError()
throws NoSuchElementException
if the source emits no items, you can check instance of thrown exception and return your custom one.
stream.filter(...)
.singleOrError()
.onErrorResumeNext(throwable -> {
if (throwable instanceof NoSuchElementException) {
return Single.error(new MyCustomException());
} else {
return Single.error(throwable);
}
});
Note that if the filter()
emits more than one item, singleOrError()
will throw IllegalArgumentException
. This can either be handled in the onErrorResumeNext()
, or by simply adding take(1)
before singleOrError()
.
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