在RxJava中过滤对象列表时处理错误



你好,我在ViewModel类中单独发出列表中的每个项目,以对返回布尔值的每个项目的字符串执行一些验证,我更新每个项目中的布尔值并返回列表。但我无法更新列表中的另一个参数作为原因,这将作为Throwable.stacktrace()

在ViewModel:

fun validateList(list: List<TestModel>): Single<List<TestModel>> {
return Observable.fromIterable(list)
.toFlowable(BackpressureStrategy.LATEST)
.map { it.jsonString }
.map { it?.let { VerifiableObject(it) } ?: throw IllegalStateException("Json must not be null") }
.flatMapSingle { validate() }
.toList()
.map {
list.mapIndexed { index, testModel ->
(if (it[index] != null) {
//Updating boolean value here
testModel.isVerified = it[index].toString()
} else throw Exception("ERROR")); testModel
}
}
}

在片段:

viewModel. validateList(arrayList)
.doFinally {
showLoading(false)
}
.asyncToUiSingle()
.subscribe({
//Updating UI
adjustCard(it)
}, {
it.printStackTrace()
})
.addTo(disposables)

TestModel:

data class TestModel(
val title: String,
var isVerified: String? = null,
var reason: String? = null)

这里我需要在reason字段中插入值,一旦任何项目例外地获得假值。如果你有什么想法,请帮助我。

如果validate引起您的麻烦,则将onErrorResumeNext应用于它并将子序列转换回原始TestModel项:

fun validateList(list: List<TestModel>): Single<List<TestModel>> {
return Observable.fromIterable(list)
.flatMapSingle { value ->
validate(VerifiableObject(value.jsonString))
.map { 
value.isVerified = it.toString
value 
}
.onErrorResumeNext {
value.reason = it.toString
Single.just(value)
}
}
.toList()
}