0

I am trying to get my head around error handling in rxjava. I thought if i combine a stream of observables for instance in a zip() function that errors emitted by the observables within the zip would break the sequence and bubble up to the subscriber onError function. However the only error caught there are the ones emmitted in the BiFunction. Errors emitted up the chain causes the system to crash. when i add onErrorReturn to the observable and return a fallback value the system still crashes. So for me that does not work as I expected. What am I missing?

private fun getOneThing (): Single<String> {
    println("getOneThing")
    if (isOneBadCondition) {
        throw Exception()      //causes crash
    } else {
        return Single.just("a string thing")
    }

}

private fun getAnotherThing(): Single<Boolean> {
    println("getAnotherThing")
    if (isAnotherBadCondition) {
        throw Exception()   //causes crash
    } else {
        return Single.just(true)
    }
}

private fun createSomethingElse (): Int {
    println("createAnother")
    if (isBadCondition) {
        throw Exception()   //is handled onError
    } else {
        return 2
    }
}

fun errorHandlingTest() {
    Single.zip(
        getOneThing(),           //if I add onErrorReturn here it is not called after error
        getAnotherThing(),       //if I add onErrorReturn here it is not called after error
        BiFunction<String, Boolean, Int> { t1, t2 ->
            createSomethingElse()
        }
    ).subscribeBy(
        onSuccess ={ println(it) },
        onError={ it.printStackTrace() })  //only error thrown by createSomethingElse() are caught here
}
Macs
  • 197
  • 2
  • 15
  • i understand now that when I do not throw the exception but wrap it in a Single.error than it works as expected. is my assumptions correct the exceptions are only caught by the subscriber onError callback if the exception is inside an observable? Why is the BiFunction exception caught in onError then? – Macs Dec 19 '19 at 12:21
  • By the way this would make sense to me since otherwise it prevents your system from crashing when it actually should – Macs Dec 19 '19 at 12:29
  • 1
    This is a common misunderstanding with how RxJava captures values or errors. You throw an exception `getOneThing` before RxJava is even involved so it would always crash no matter if you even have RxJava in your project or not. BiFunction is called by RxJava when the flow is active thus it will deliver its crash to the `onError` handler. – akarnokd Dec 19 '19 at 14:11

0 Answers0