architecture-components-samples
architecture-components-samples copied to clipboard
Observing LiveData instance from View ?
HI is it safe to observe a LiveData instance stored in ViewModel directly from a View ?
This what i'm doing, it's working, but i don't know if i'am missing some implications of doing this.
@BindingAdapter("stateLive")
fun <T> AsyncLayout.setStateLive(stateLive: LiveData<Resource<T>>?) {
stateLive?.apply {
val observer: Observer<Resource<T>> = Observer { it ->
it?.apply {
if (isLoading) {
state = AsyncLayout.State.LOADING
return@Observer
}
state = if (success()) AsyncLayout.State.SUCCESS else AsyncLayout.State.ERROR
}
}
observeForever(observer)
onDestroyView = {
stateLive.removeObserver(observer)
}
}
}
You can check more details here https://stackoverflow.com/questions/52844569/observing-livedata-instance-from-view