Multiple calls to set LiveData is not observed

后端 未结 5 1039
闹比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 19:13

    You should call viewModel.fetchFirstThree() after Activity's onStart() method. for example in onResume() method.

    Because in LiveData the Observer is wrapped as a LifecycleBoundObserver. The field mActive set to true after onStart().

    class LifecycleBoundObserver extends ObserverWrapper implements GenericLifecycleObserver {
    
        @Override
        boolean shouldBeActive() {
            return mOwner.getLifecycle().getCurrentState().isAtLeast(STARTED);// return true after onStart()
        }
        @Override
        public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
            if (mOwner.getLifecycle().getCurrentState() == DESTROYED) {
                removeObserver(mObserver);
                return;
            }
            activeStateChanged(shouldBeActive());// after onStart() change mActive to true
        }
    }
    

    When the observer notify the change it calls considerNotify, before onStart it will return at !observer.mActive

     private void considerNotify(ObserverWrapper observer) {
        if (!observer.mActive) {// called in onCreate() will return here.
            return;
        }
        if (!observer.shouldBeActive()) {
            observer.activeStateChanged(false);
            return;
        }
        if (observer.mLastVersion >= mVersion) {
            return;
        }
        observer.mLastVersion = mVersion;
        //noinspection unchecked
        observer.mObserver.onChanged((T) mData);
    }
    

提交回复
热议问题