How to handle error states with LiveData?

后端 未结 7 619
暗喜
暗喜 2020-12-07 14:10

The new LiveData can be used as a replacement for RxJava\'s observables in some scenarios. However, unlike Observable, LiveData has no callback for

7条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-07 15:07

    In my app, I had to translate RxJava Observables into LiveData. While doing that, I of course had to maintain the error state. Here's how I did it (Kotlin)

    class LiveDataResult(val data: T?, val error: Throwable?)
    
    class LiveObservableData(private val observable: Observable) : LiveData>() {
        private var disposable = CompositeDisposable()
    
        override fun onActive() {
            super.onActive()
    
            disposable.add(observable.subscribe({
                postValue(LiveDataResult(it, null))
            }, {
                postValue(LiveDataResult(null, it))
            }))
        }
    
        override fun onInactive() {
            super.onInactive()
    
            disposable.clear()
        }
    }
    

提交回复
热议问题