android-如何使用LiveData和RxJava处理错误?
我是新来学习的,我已经在这个问题上纠缠了好几天了 我用它来转换Livedata和Flowable,除了处理RxJava的onError之外,它们都工作得很好android-如何使用LiveData和RxJava处理错误?,android,kotlin,rx-java,android-livedata,Android,Kotlin,Rx Java,Android Livedata,我是新来学习的,我已经在这个问题上纠缠了好几天了 我用它来转换Livedata和Flowable,除了处理RxJava的onError之外,它们都工作得很好 livedata = LiveDataReactiveStreams.fromPublisher( // bookRepository.getAll() return a Flowable bookRepository.getAll().map {
livedata = LiveDataReactiveStreams.fromPublisher(
// bookRepository.getAll() return a Flowable
bookRepository.getAll().map {
val allBookNames = mutableListOf<String>()
it.forEach {
allBookNames.add(it.name)
}
return@map allBookNames.toList()
}
)
livedata=LiveDataReactiveStreams.fromPublisher(
//getAll()返回一个可流动的
bookRepository.getAll().map{
val allBookNames=mutableListOf()
这是forEach{
allBookNames.add(it.name)
}
return@mapallBookNames.toList()
}
)
我看到了,我想我能做到
LiveDataReactiveStreams.fromPublisher(
LiveDataReactiveStreams.fromPublisher(
Observable.just(1,2)
.map { LiveDataResult(it, null) }
.onErrorReturn {
it.printStackTrace()
LiveDataResult(null, it)
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.toFlowable(BackpressureStrategy.MISSING)
class LiveDataResult<T>(val data: T?, val error: Throwable?)
可观测的。仅(1,2)
.map{LiveDataResult(it,null)}
A.报税表{
it.printStackTrace()
LiveDataResult(null,it)
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.toFlowable(背压等级缺失)
类LiveDataResult(val数据:T?,val错误:可丢弃?)
然后你可以处理结果或错误我认为你需要使用LiveData而不是RxJava。它们都是可观察的。@Hades但LiveData也不提供任何处理错误的函数。这取决于
bookRepository.getAll()的实现
方法,您可以将错误回调作为参数传递到那里,并将调用更改为以下内容:bookRepository.getAll({//Handle error here}).map{//Handle success here}.etc。使用这种方法,getAll()
方法将在出错时触发回调并返回null,或者在成功时返回书籍