android LiveData学习

看了这篇文章能够明白哪几个问题?

  1. LiveData如何实现数据监听的
  2. LiveData的setValue和postValue有什么区别?
  3. 数据被设置后,在通知到observer之前,会进行那些操作
  4. foreverObserve与observe有什么区别?

看看源码,分析分析

LiveData是一个抽象类,定义如下:
public abstract class LiveData
使用的时候一般使用其子类,如下:


livedata.png

其中mutableLiveData比较常用

首先看下observe的代码

   //**主线程设置observe**
    @MainThread
//**参数需要lifecycleOwner,往往使用的时候会传入activity,第二个参数是一个observer**
    public void observe(@NonNull LifecycleOwner owner, @NonNull Observer observer) {
        assertMainThread("observe");
        //**如果状态为destoryed,则返回**
        if (owner.getLifecycle().getCurrentState() == DESTROYED) {
            // ignore
            return;
        }
        //**LifecycleBoundObserver继承了ObserverWrap和LifecycleEventObserver**
        LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
        //**map entry结构,如果已经存在,则返回非空,不存在则返回null**
        ObserverWrapper existing = mObservers.putIfAbsent(observer, wrapper);
         //**如果已经存在,并且之前的oberserve还没有attach,则抛出异常**
        if (existing != null && !existing.isAttachedTo(owner)) {
            throw new IllegalArgumentException("Cannot add the same observer"
                    + " with different lifecycles");
        }
         //**如果已经存在,return,无需重复添加Observer**
        if (existing != null) {
            return;
        }
        //**为Owner添加Observer,也就是我们的activity或者fragment,所以当activity生命周期发生变化时,就可以在LifecycleBoundObserver的onstatechange进行对应的逻辑处理**
        owner.getLifecycle().addObserver(wrapper);
    }

看下LifecycleBoundObserver的生命周期感知逻辑

class LifecycleBoundObserver extends ObserverWrapper implements LifecycleEventObserver {
        @NonNull
        final LifecycleOwner mOwner;

        LifecycleBoundObserver(@NonNull LifecycleOwner owner, Observer observer) {
            super(observer);
            mOwner = owner;
        }

        @Override
        boolean shouldBeActive() {
            return mOwner.getLifecycle().getCurrentState().isAtLeast(STARTED);
        }

        @Override
        public void onStateChanged(@NonNull LifecycleOwner source,
                @NonNull Lifecycle.Event event) {
            Lifecycle.State currentState = mOwner.getLifecycle().getCurrentState();
            if (currentState == DESTROYED) {
                removeObserver(mObserver);
                return;
            }
            //**进行状态通知,需要确保当前状态已经与owner的当前状态一致,所以用了while**
            Lifecycle.State prevState = null;
            while (prevState != currentState) {
                prevState = currentState;
                //**主要逻辑**
                activeStateChanged(shouldBeActive());
                currentState = mOwner.getLifecycle().getCurrentState();
            }
        }

        @Override
        boolean isAttachedTo(LifecycleOwner owner) {
            return mOwner == owner;
        }

        @Override
        void detachObserver() {
            mOwner.getLifecycle().removeObserver(this);
        }
    }

看下activieStateChange逻辑

void activeStateChanged(boolean newActive) {
            //**记录owner是否active以保证下一步的changeActiveCounter只有在状态变化的时候执行**
            if (newActive == mActive) {
                return;
            }
            // immediately set active state, so we'd never dispatch anything to inactive
            // owner
            mActive = newActive;
            //**这个主要是给一些后台下载用的,比如MutableLiveData的子类LoaderInfo,用于在owner active或者pause的时候进行下载任务的暂停与开始逻辑**
            changeActiveCounter(mActive ? 1 : -1);
            //**保证只有在active的情况下,才进行数据更新通知**
            if (mActive) {
                dispatchingValue(this);
            }
        }

看下dispatchingValue逻辑。这个也是setValue和postValue的核心

@SuppressWarnings("WeakerAccess") /* synthetic access */
    void dispatchingValue(@Nullable ObserverWrapper initiator) {
        if (mDispatchingValue) {
            mDispatchInvalidated = true;
            return;
        }
        mDispatchingValue = true;
        do {
            mDispatchInvalidated = false;
            //**lifecycle statechange的时候会走此逻辑,此时是单个observer的更新**
            if (initiator != null) {
                considerNotify(initiator);
                initiator = null;
             //**setvalue的时候会走此逻辑,此时是所有observer的更新**
            } else {
                for (Iterator, ObserverWrapper>> iterator =
                        mObservers.iteratorWithAdditions(); iterator.hasNext(); ) {
                    considerNotify(iterator.next().getValue());
                    if (mDispatchInvalidated) {
                        break;
                    }
                }
            }
        } while (mDispatchInvalidated);
        mDispatchingValue = false;
    }

看看considerNotify(iterator.next().getValue());就比较简单了

 @SuppressWarnings("unchecked")
    private void considerNotify(ObserverWrapper observer) {
        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;
        //**通知了**
        observer.mObserver.onChanged((T) mData);
    }

至此obseve的逻辑到此结束,也就是主要流程已经完成了

我们再看下setValue和postValue的区别

private final Runnable mPostValueRunnable = new Runnable() {
        @SuppressWarnings("unchecked")
        @Override
        public void run() {
            Object newValue;
            synchronized (mDataLock) {
                newValue = mPendingData;
                mPendingData = NOT_SET;
            }
            setValue((T) newValue);
        }
    };

protected void postValue(T value) {
        boolean postTask;
        synchronized (mDataLock) {
            postTask = mPendingData == NOT_SET;
            mPendingData = value;
        }
        if (!postTask) {
            return;
        }
          //**使用ArchTaskExecutor直接post到主线程了。最终也是通过setvalue进行数据更新**
        ArchTaskExecutor.getInstance().postToMainThread(mPostValueRunnable);
    }

    /**
     * Sets the value. If there are active observers, the value will be dispatched to them.
     * 

* This method must be called from the main thread. If you need set a value from a background * thread, you can use {@link #postValue(Object)} * * @param value The new value */ @MainThread protected void setValue(T value) { assertMainThread("setValue"); mVersion++; mData = value; //**该方法,上面流程已经介绍了,不多说** dispatchingValue(null); }

其实也就是一个是主线程(setValue),一个是子线程的使用(postValue)

我们再看下foreverObserve,这个是什么鬼

其实,里面最主要的区别就是使用了AlwaysActiveObserver而非LifecycleBound Observer,看下其实现

@MainThread
//参数没有LifecycleOwner
    public void observeForever(@NonNull Observer observer) {
        assertMainThread("observeForever");
        //这里不一样
        AlwaysActiveObserver wrapper = new AlwaysActiveObserver(observer);
        ObserverWrapper existing = mObservers.putIfAbsent(observer, wrapper);
        if (existing instanceof LiveData.LifecycleBoundObserver) {
            throw new IllegalArgumentException("Cannot add the same observer"
                    + " with different lifecycles");
        }
        if (existing != null) {
            return;
        }
        wrapper.activeStateChanged(true);
    }


    private class AlwaysActiveObserver extends ObserverWrapper {

        AlwaysActiveObserver(Observer observer) {
            super(observer);
        }

        @Override
        //可以看到,这里一直是true的,也就是不会受activity生命周期影响,而有点类似static变量作用域
        boolean shouldBeActive() {
            return true;
        }
    }

回顾一下刚开始的四个问题

其中1、2、4都比较明确了,关于第3点 再看下
数据被设置后,在通知到observer之前,会进行那些操作?
其实这里就行了三点,也就是主要considerNotify的逻辑

  1. observer是否active
  2. observer已经处于actvie状态,但是没有收到该变化,异常情况
  3. 版本问题,老版本大于当前版本
    没有以上问题,那就进行通知

你可能感兴趣的:(android LiveData学习)