architecture-components-samples icon indicating copy to clipboard operation
architecture-components-samples copied to clipboard

Observing LiveData instance from View ?

Open Sserra90 opened this issue 7 years ago • 0 comments

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

Sserra90 avatar Oct 17 '18 10:10 Sserra90