Michael Friend
08/03/2020, 6:24 PMliveData
coroutine builder suited for retrying/refreshing data loads or does everyone typically avoid it when you need that functionality? I’ve started using it recently to lazily load data when needed by the UI, but i cant come up with a clean way of using liveData
while also being able to refresh the data (i.e. when coming back to the screen) or retry failed operations. Typically my ViewModels look something like:
val data: LiveData<State<MyData>> = liveData {
emit(Loading)
try {
emit(getData())
catch (e: SomeEx) {
emit(Error(e))
}
}
suspend fun getData(): MyData {...}
But with this i have no way of actually retrying the operation and emitting to the LiveData again if it fails. And in the cases i need to update the data on user events like a refresh button or returning to the screen I’m stuck with the stale data.Michael Friend
08/03/2020, 6:27 PMokarm
08/03/2020, 7:43 PMLiveData
, I'd experiment with a setup similar to the following:
private val performLoad = MutableLiveData(Unit)
val data: LiveData<State<MyData>> = performLoad.switchMap {
liveData {
emit(Loading)
try {
emit(getData())
catch (e: SomeEx) {
emit(Error(e))
}
}
}
suspend fun getData(): MyData {...}
fun performLoad() = performLoad.postValue(Unit)
Michael Friend
08/04/2020, 1:42 PMLiveData
is there something you had in mind that can be done with Flow or something else? Or are you referring to the liveData
coroutine builder?okarm
08/04/2020, 1:50 PMLiveData
type. It's just a philosophical question - Lately I migrated away from LiveData
, especially in deeper layers behind a ViewModel. I don't like coupling domain with Android libraries. Google recognizes the limitations of LiveData, so they started pushing Flow instead of LiveData as well.
But the pattern would be very similar with all other options. Observe some sort of separate command channel/livedata/flow and flatmap/switchmap to produce a fresh flow/livedata each time a command is received.Michael Friend
08/04/2020, 1:57 PM