因此,我在RxJava中使用flatMap来链接一些返回Singles的API调用,并且想知道如何根据我自己的条件将自定义throwable传递给flatmap方法中的subscription方法。
这是在使用MVVM和RxJava2/RxAndroid进行数据操作的Android Kotlin应用程序中。我试图将一堆使用flatmap方法返回Singles的API调用链接在一起。每次,我想在上一个方法之后调用一个新的API方法,我想检查一下上一个调用的响应是否成功。如果前一个调用的响应成功,我只是在平面图中调用了下一个API方法,一切都很好,但是如果前一个调用的响应没有成功,我想传递一个自定义的throwable来告诉我该操作在何处以及为什么执行不了。不成功。现在,在响应未成功的情况下,我传递了一个带有null值的Single,但这在订阅时仅给了我一个null指针,这并不是很有帮助。
dataManager.apiCall1(dataManager.sessionId!!)
.subscribeOn(schedulerProvider.io())
.observeOn(schedulerProvider.ui())
.flatMap{apiCall1Response ->
if (apiCall1Response.isSuccessful && apiCall1Response.body() != null) {
// First api call was successful, execute api call 2.
return@flatMap dataManager.apiCall2(apiCall1Response.importantVal)
} else {
// First api call failed
Single.just(null)
}
}.flatMap{apiCall2Response ->
if (apiCall2Response != null && apiCall2Response.isSuccessful && apiCall2Response.body() != null) {
// Second api call was successful, execute api call 3.
return@flatMap dataManager.apiCall3(apiCall2Response.importantVal)
} else {
// Second api call failed
Single.just(null)
}
}.subscribe({apiCall3Response ->
if (apiCall3Response != null && apiCall3Response.body() != null) {
// Success!
navigator!!.successful(response)
} else {
// Third api call failed, handle error
navigator!!.handleError(Throwable("Api call 3 failed."))
}
}, {throwable ->
// Failure, this is where I want to receive a custom throwable
// in case one of the responses were unsuccessful.
navigator!!.handleError(throwable)
})
我希望throwable消息像“apiCall1”失败一样,但是由于我传递的Single.just(null),apiCall1失败时的throwable消息只是NullPointer。
最佳答案
代替Single.just(null)
,使用Single.error()
。
例如:Single.error<TypeHere>(RuntimeException("First api call failed"))
关于android - 如何在Android上的RxJava中通过平面图向下发送自定义可弃项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54259876/