https://kotlinlang.org logo
#android-architecture
Title
# android-architecture
h

Hitanshu Dhawan

12/28/2019, 9:29 AM
Hey guys, I am using LiveData coroutines KTX extension for my project. https://developer.android.com/topic/libraries/architecture/coroutines#livedata The code is something like this.
ViewModel/Repository
Copy code
fun getData() = liveData {
    val a = getFromDB()
    emit(a)
    val b = getFromNetwork()
    emit(b)
}
View
Copy code
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.
v

voben

12/29/2019, 12:39 AM
In viewmodel
Copy code
val 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
Copy code
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 livedata
h

Hitanshu Dhawan

12/29/2019, 9:26 PM
Thanks @voben for the reply. Yes, this method works perfectly. But I was looking something with the
liveData {}
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 🤔
v

voben

12/29/2019, 9:37 PM
The Livedata builder is cold and only emits when the user starts observing it. So the only way to emit again would be by detaching and reattaching the observer or by attaching a new one https://developer.android.com/topic/libraries/architecture/coroutines#livedata
10 Views