我试图了解 rxjava 中的错误处理。我想如果我在一个 zip() 函数中组合一个 observables 流,那么 zip 中的 observables 发出的错误会破坏序列并冒泡到订阅者 onError 函数。然而,唯一捕获的错误是 BiFunction 中发出的错误。链上发出的错误会导致系统崩溃。当我将 onErrorReturn 添加到可观察对象并返回后备值时,系统仍然崩溃。所以对我来说,这并不像我预期的那样工作。我错过了什么?
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
}