Hitanshu Dhawan
12/28/2019, 9:29 AMViewModel/Repository
fun getData() = liveData {
val a = getFromDB()
emit(a)
val b = getFromNetwork()
emit(b)
}
View
viewModel.getData().observe(this, Observer{
// do ui stuff
})
This works perfectly fine. But the problem is now I want to add Swipe to Refresh feature, and want that the entire liveData {}
block to run again.
How do I trigger a refresh call to the getData()
LiveData?
One solution which is mentioned here (https://stackoverflow.com/a/58689791) is to introduce another MediatorLiveData
and remove and re-add the liveData {}
block on refresh. But I don't want to add 2 LiveDatas and it also seems like a hack.
Any good and elegant solution for this guys? Thanks.voben
12/29/2019, 12:39 AMval myLiveData = MutableLiveData() // This is a class property in your viewmodel
fun doFetch() {
val a = getFromDB()
myLiveData.value = a
val b = getFromNetwork()
myLiveData.value = b
}
and in your View class
viewModel.myLiveData.observe(this, Observer{
// do ui stuff
})
// Calling `doFetch()` will redo the operation and set the livedata values
As an improvement, consider also exposing myLiveData to the view as an immutable livedataHitanshu Dhawan
12/29/2019, 9:26 PMliveData {}
block, which supports coroutines.
Is it possible to use the liveData {}
block with refresh functionality? Or should I not use liveData {}
block?
I'm little bit confused 🤔voben
12/29/2019, 9:37 PM