Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/206.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
android-如何使用LiveData和RxJava处理错误?_Android_Kotlin_Rx Java_Android Livedata - Fatal编程技术网

android-如何使用LiveData和RxJava处理错误?

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和Flowable,除了处理RxJava的onError之外,它们都工作得很好

        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()
}
)
我看到了,我想我能做到

  • 包装我的数据以处理我的错误

  • 或者像@所说的那样使用MediatorLiveData,但还有一个问题是永远不会调用Flowable onComplete()

  • 有没有更好的方法来解决这个问题,或者我忽略了这两个解决方案的细节

    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,或者在成功时返回书籍