Observing LiveData instance from View

544 Views Asked by At

I created a ViewGroup that updates it's contents based on the state of a LiveData instance, however i don't know if observing a LiveData instance in a view can cause some problems ?

This is the code i'am using, it removes the observer when onDestroyView is called.

@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)
        }
    }
}

The view shows an error, loading or content view based on the state received from LiveData, in XML i can use it like this:

    <com.common.views.AsyncLayout
        android:id="@+id/asyncLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:stateLiveData="@{vm.someLiveData}">

         //Content view
         <TextView> ...
    <com.common.views.AsyncLayout>

This way i can reuse this layout that already has animations, loading and an error view without duplicating code in Activities or Fragments. But i have that question about observing a LiveData by a view, i think it's safe to do it because it removes itself when the view is destroyed, however i may be missing other implications of doing this.

0

There are 0 best solutions below