Search code examples
javarx-java2

handle checked exception in RxJava 2


I have some issue when I try to catch exception.

I have some method like this (legacy method) :

public String myLegacyMethod throws MyException() {
//do something or throw MyException in case of error
}

and I need to send a Single of this part and my solution is:

public Single<String> reactiveMethod() {
 try {
  String s = myLegacyMethod();
  return Single.just(s);
 } catch (Exception e) {
  //log exception
  return Single.error(e);
 }
}

are there a way to handle an exception in reactive way? or maybe transform reactiveMethod in non-blocking code?

thanks for your answers.


Solution

  • You can use fromCallable in 2.x if MyException extends Exception:

    public Single<String> reactiveMethod() {
      return Single.fromCallable(() -> myLegacyMethod());
    }