The new LiveData can be used as a replacement for RxJava\'s observables in some scenarios. However, unlike Observable, LiveData has no callback for
Another approach is to use MediatorLiveData that will take sources of LiveData of different type. This will give you separation of each event:
For example:
open class BaseViewModel : ViewModel() {
private val errorLiveData: MutableLiveData = MutableLiveData()
private val loadingStateLiveData: MutableLiveData = MutableLiveData()
lateinit var errorObserver: Observer
lateinit var loadingObserver: Observer
fun fromPublisher(publisher: Publisher): MediatorLiveData {
val mainLiveData = MediatorLiveData()
mainLiveData.addSource(errorLiveData, errorObserver)
mainLiveData.addSource(loadingStateLiveData, loadingObserver)
publisher.subscribe(object : Subscriber {
override fun onSubscribe(s: Subscription) {
s.request(java.lang.Long.MAX_VALUE)
loadingStateLiveData.postValue(LoadingState.LOADING)
}
override fun onNext(t: T) {
mainLiveData.postValue(t)
}
override fun onError(t: Throwable) {
errorLiveData.postValue(t)
}
override fun onComplete() {
loadingStateLiveData.postValue(LoadingState.NOT_LOADING)
}
})
return mainLiveData
}
}
In this example loading and error LiveData will start being observed once the MediatorLiveData will have active observers.