LiveData讲解

LiveData讲解

MutableLiveData

MutableLiveData代码

/**
 * {@link LiveData} which publicly exposes {@link #setValue(T)} and {@link #postValue(T)} method.
 *
 * @param <T> The type of data hold by this instance
 */
@SuppressWarnings("WeakerAccess")
public class MutableLiveData<T> extends LiveData<T> {
    @Override
    public void postValue(T value) {
        super.postValue(value);
    }

    @Override
    public void setValue(T value) {
        super.setValue(value);
    }
}

LiveData类中的这两个方法是protected.

MutableLiveData将LiveData的postValue()和setvalue()公开化。

LiveData源码分析

    @MainThread
    public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer) {
        assertMainThread("observe");
        
        // 如果当前lifecycle已经被摧毁 则直接返回 添加观察者失败
        if (owner.getLifecycle().getCurrentState() == DESTROYED) {
            // ignore
            return;
        }
        ---------------->分析1
        LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
        ------------------》分析2
        ObserverWrapper existing = mObservers.putIfAbsent(observer, wrapper);
        
        if (existing != null && !existing.isAttachedTo(owner)) {
            throw new IllegalArgumentException("Cannot add the same observer"
                    + " with different lifecycles");
        }
        if (existing != null) {
            return;
        }
        ---------------->
        观察者观察lifecycle的状态变化
         @Override
        public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
            if (mOwner.getLifecycle().getCurrentState() == DESTROYED) {
                removeObserver(mObserver);
                return;
            }
            activeStateChanged(shouldBeActive());
        }
        如果lifecycle状态变为destroyed则移除观察者,避免了内存泄漏。
        否则进入activeStateChanged(shouldBeActive())方法。

        void activeStateChanged(boolean newActive) {
            if (newActive == mActive) {
                return;
            }
            // immediately set active state, so we'd never dispatch anything to inactive
            // owner
            mActive = newActive;
            boolean wasInactive = LiveData.this.mActiveCount == 0;
            LiveData.this.mActiveCount += mActive ? 1 : -1;
            if (wasInactive && mActive) {
                onActive();
            }
            if (LiveData.this.mActiveCount == 0 && !mActive) {
                onInactive();
            }
            --------> 如果mActive为真,则分发value
            if (mActive) {
                // 区别于传入的参数为null,本次只会回调这个observerconsiderNotify()
                dispatchingValue(this);
            }
        }
        --------------->
         void dispatchingValue(@Nullable ObserverWrapper initiator) {
        if (mDispatchingValue) {
            mDispatchInvalidated = true;
            return;
        }
        mDispatchingValue = true;
        do {
            mDispatchInvalidated = false;
            if (initiator != null) {
                considerNotify(initiator);
                initiator = null;
            } else {
                for (Iterator<Map.Entry<Observer<? super T>, ObserverWrapper>> iterator =
                        mObservers.iteratorWithAdditions(); iterator.hasNext(); ) {
                    considerNotify(iterator.next().getValue());
                    if (mDispatchInvalidated) {
                        break;
                    }
                }
            }
        } while (mDispatchInvalidated);
        mDispatchingValue = false;
    }
        --------------->

        ------------------>
        owner.getLifecycle().addObserver(wrapper);
    }

    -------分析1

    LifecycleBoundObserver类 对Obser对象进行封装 并观察 该类持有组件,他的父类ObserverWrapper持有observer对象
    class LifecycleBoundObserver extends ObserverWrapper implements GenericLifecycleObserver{
             @Override
        boolean shouldBeActive() {  
            return mOwner.getLifecycle().getCurrentState().isAtLeast(STARTED);
        }
=====================================================================
        mOwner就是observe方法被调用是传入的lifecycleOwner对象,isAtLeast(STARTED)用来比较当前lifecycle的状态是否为started,


                /**
         * Started state for a LifecycleOwner. For an {@link android.app.Activity}, this state
         * is reached in two cases:
         * <ul>
         *     <li>after {@link android.app.Activity#onStart() onStart} call;
         *     <li><b>right before</b> {@link android.app.Activity#onPause() onPause} call.
         * </ul>
         */
        STARTED,
=================================================================================================
        


    }
    public interface GenericLifecycleObserver extends LifecycleEventObserver{}
    public interface LifecycleEventObserver extends LifecycleObserver {
        /**
        * Called when a state transition event happens.
        *
        * @param source The source of the event
        * @param event The event
        */
        void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event);
    }

    owner.getLifecycle().addObserver(wrapper) 用来观察lifecycle的生命周期

-----------》分析2
将该liveData所有的observer记录起来
private SafeIterableMap<Observer<? super T>, ObserverWrapper> mObservers = new SafeIterableMap<>();

postValue和setValue的区别

    protected void postValue(T value) {
        boolean postTask;
        synchronized (mDataLock) {
            postTask = mPendingData == NOT_SET;
            //mPendingData临时储存value
            mPendingData = value;
        }
        if (!postTask) {
            return;
        }
        切换到主线程执行
        ArchTaskExecutor .getInstance().postToMainThread(mPostValueRunnable);
    }

    private final Runnable mPostValueRunnable = new Runnable() {
        @Override
        public void run() {
            Object newValue;
            synchronized (mDataLock) {
                newValue = mPendingData;
                // 清空
                mPendingData = NOT_SET;
            }

            // 调用setValue()方法 noinspection unchecked
            setValue((T) newValue);
        }
    };
----------->
     @MainThread
    protected void setValue(T value) {
        assertMainThread("setValue");
        mVersion++;
        mData = value;
        // 便利observers分发-----> 传入null跳转到分析3
        dispatchingValue(null);
    }
----------->
在setValue()中会首先判断当前是否为主线程,不是则抛出异常
  private static void assertMainThread(String methodName) {
        if (!ArchTaskExecutor.getInstance().isMainThread()) {
            throw new IllegalStateException("Cannot invoke " + methodName + " on a background"
                    + " thread");
        }
    }

  ---------->分析3
private void considerNotify(ObserverWrapper observer) {
    // 如果当前组件不是在start--与resume之间则直接返回
        if (!observer.mActive) {
            return;
        }
        // Check latest state b4 dispatch. Maybe it changed state but we didn't get the event yet.
        //
        // we still first check observer.active to keep it as the entrance for events. So even if
        // the observer moved to an active state, if we've not received that event, we better not
        // notify for a more predictable notification order.
        
        if (!observer.shouldBeActive()) {
            observer.activeStateChanged(false);
            return;
        }

        if (observer.mLastVersion >= mVersion) {
            return;
        }
        observer.mLastVersion = mVersion;
        //noinspection unchecked
        observer.mObserver.onChanged((T) mData);
    }

LiveData的observer被回调只有在

  • LiveData的setValue()或者postValue()方法被调用。
  • Observer被添加到LiveData上或者onStateChanged()方法被调用的时候。

关于observer可以回调在它被设置之前postValue(),setValue()的值

  • 每个Observerser封装类都会有一个mLastVerson(默认为-1)
  • liveData内部会有一个mVerson(默认为-1)

在setValue()中mVerson会++,在considerNotify()方法中如果可以回调则先将mVerson赋值给observer的mLastVerson然后完成observer的回调。

原文地址:https://www.cnblogs.com/FCY-LearningNotes/p/13922711.html