Consider the following example:
Observable.range(1, 10).subscribe(i -> {
System.out.println(i);
if (i == 5) {
throw new RuntimeException("oops!");
}
}, Throwable::printStackTrace);
This outputs numbers from 1 to 5 and then prints the exception.
What I want to achieve is make the observer stay subscribed and continue to run after throwing an exception, i.e. print all numbers from 1 to 10.
I have tried using retry()
and other various error handling operators, but, as said in the documentation, their purpose is handling errors emitted by the observable itself.
The most straightforward solution is just to wrap the whole body of onNext
into a try-catch block, but that doesn't sound like a good solution to me. In the similar Rx.NET question, the proposed solution was to make an extension method which would do the wrapping by creating a proxy observable. I tried to remake it:
Observable<Integer> origin = Observable.range(1, 10);
Observable<Integer> proxy = Observable.create((Observable.OnSubscribe<Integer>) s ->
origin.subscribe(i -> {try { s.onNext(i); } catch (Exception ignored) {}}, s::onError, s::onCompleted));
proxy.subscribe(i -> {
System.out.println(i);
if (i == 5) {
throw new RuntimeException("oops!");
}
}, Throwable::printStackTrace);
This does not change anything, because RxJava itself wraps the subscriber into a SafeSubscriber
. Using unsafeSubscribe
to get around it doesn't seem to be a good solution either.
What can I do to solve this problem?