Multiple calls to set LiveData is not observed

后端 未结 5 1074
闹比i
闹比i 2021-01-11 18:28

I have recently seen a weird issue that is acting as a barrier to my project. Multiple calls to set the live data value does not invoke the observer in the view.

It

5条回答
  •  無奈伤痛
    2021-01-11 18:52

    I did some science, re-implementing LiveData and MutableLiveData to log out some data.

    Check the source code here.

    setValue value=Test1
    dispatchingValue mDispatchingValue=false mDispatchInvalidated=false
    considerNotify
    Returned at !observer.active
    setValue value=Test2
    dispatchingValue mDispatchingValue=false mDispatchInvalidated=false
    considerNotify
    Returned at !observer.active
    setValue value=Test3
    dispatchingValue mDispatchingValue=false mDispatchInvalidated=false
    considerNotify
    Returned at !observer.active
    dispatchingValue mDispatchingValue=false mDispatchInvalidated=false
    considerNotify
    ITEM: Test3
    

    It looks like the observer hasn't reached an active state when you send the initial values.

    private void considerNotify(LifecycleBoundObserver observer) {
        // <-- Three times it fails here. This means that your observer wasn't ready for any of them.
        if (!observer.active) {
            return;
        }
    

    Once the observer reaches an active state, it sends the last set value.

    void activeStateChanged(boolean newActive) {
        if (newActive == active) {
            return;
        }
        active = newActive;
        boolean wasInactive = LiveData.this.mActiveCount == 0;
        LiveData.this.mActiveCount += active ? 1 : -1;
        if (wasInactive && active) {
            onActive();
        }
        if (LiveData.this.mActiveCount == 0 && !active) {
            onInactive();
        }
        if (active) {
            // <--- At this point you are getting a call to your observer!
            dispatchingValue(this);
        }
    }
    

提交回复
热议问题