Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava emit error on empty

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.

like image 870
Raipe Avatar asked Jan 01 '17 17:01

Raipe


1 Answers

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().

like image 181
Alexander Perfilyev Avatar answered Sep 24 '22 02:09

Alexander Perfilyev