Error handling rxjava zip函数中未从观察值冒泡的错误
我正试图了解rxjava中的错误处理。我认为,如果我将一个可观测数据流(例如在zip()函数中)组合在一起,zip中的可观测数据发出的错误将破坏序列并冒泡到订阅方onError函数。然而,在那里捕捉到的唯一错误是在双函数中出现的错误。链上发出的错误会导致系统崩溃。当我将OneRorReturn添加到observable并返回一个回退值时,系统仍然崩溃。所以对我来说,这并不像我预期的那样有效。我错过了什么Error handling rxjava zip函数中未从观察值冒泡的错误,error-handling,rx-java2,rx-kotlin2,Error Handling,Rx Java2,Rx Kotlin2,我正试图了解rxjava中的错误处理。我认为,如果我将一个可观测数据流(例如在zip()函数中)组合在一起,zip中的可观测数据发出的错误将破坏序列并冒泡到订阅方onError函数。然而,在那里捕捉到的唯一错误是在双函数中出现的错误。链上发出的错误会导致系统崩溃。当我将OneRorReturn添加到observable并返回一个回退值时,系统仍然崩溃。所以对我来说,这并不像我预期的那样有效。我错过了什么 private fun getOneThing (): Single<String&g
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
}
private fun getOneThing():单人{
println(“getOneThing”)
if(isOneBadCondition){
抛出异常()//导致崩溃
}否则{
返回Single.just(“字符串对象”)
}
}
私人娱乐getAnotherThing():单身{
println(“获取其他信息”)
如果(是其他条件){
抛出异常()//导致崩溃
}否则{
返回单曲。刚刚(正确)
}
}
private fun createSomethingElse():Int{
println(“创建另一个”)
如果(isBadCondition){
throw Exception()//已在错误中处理
}否则{
返回2
}
}
有趣的错误处理测试(){
Single.zip(
getOneThing(),//如果在此处添加onErrorReturn,则在出错后不会调用它
getAnotherThing(),//如果在此处添加onErrorReturn,则在出错后不会调用它
双功能{t1,t2->
createSomethingElse()
}
).订阅人(
onSuccess={println(it)},
onError={it.printStackTrace()})//这里只捕获createSomethingElse()抛出的错误
}
我现在明白了,如果我不抛出异常,而是将其包装在一个单独的.error中,那么它会比预期的效果更好。我的假设正确吗?如果异常在可观察范围内,则只有订阅者onError回调才能捕获异常?为什么双功能异常会在OneError中被捕获?顺便说一句,这对我来说是有意义的,因为否则它可以防止系统在实际应该崩溃时崩溃。这是对RxJava如何捕获值或错误的常见误解。在涉及RxJava之前抛出异常getOneThing
,因此无论项目中是否有RxJava,它都会崩溃。当流处于活动状态时,RxJava会调用BiFunction,因此它会将崩溃传递给onError
处理程序。