Android LiveData原理分析

从API调用入手

举个栗子:Activity中订阅数据变更

    viewModel.contentLiveData.observe(this, Observer<String> { content ->
        tv.text = content
    })

ViewModel中初始化LiveData

    val contentLiveData: MutableLiveData<String> by lazy {
        MutableLiveData<String>()
    }

LiveData.observe()

    public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer) {
        //检查是否为ui线程
        assertMainThread("observe");
        //页面DESTROYED状态不执行订阅流程
        if (owner.getLifecycle().getCurrentState() == DESTROYED) {
            return;
        }
        //包装
        LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
        //添加到集合mObservers
        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;
        }
        owner.getLifecycle().addObserver(wrapper);
    }

owner为上述this--->Activity,owner和用户自定义的observer包装到LifecycleBoundObserver

LifeCycle原理分析过Activity.getLifecycle()返回LifecycleRegistry--->LifecycleRegistry.addObserver(wrapper)

LifecycleBoundObserver实现LifecycleEventObserver接口

    class LifecycleBoundObserver extends ObserverWrapper implements LifecycleEventObserver{
        final LifecycleOwner mOwner;

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

        @Override
        public void onStateChanged(@NonNull LifecycleOwner source,
                @NonNull Lifecycle.Event event) {
            if (mOwner.getLifecycle().getCurrentState() == DESTROYED) {
                removeObserver(mObserver);
                return;
            }
            activeStateChanged(shouldBeActive());
        }
    }

owner生命周期变更时会触发onStateChanged()方法,DESTROYED状态移除订阅。

接下来触发数据变更

    contentLiveData.value = ""
MutableLiveData.setValue()
    @Override
    public void setValue(T value) {
        super.setValue(value);
    }

调用父类LiveData.setValue()

    protected void setValue(T value) {
        assertMainThread("setValue");
        mVersion++;
        mData = value;
        dispatchingValue(null);
    }

LiveData.dispatchingValue()

    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;
    }

遍历集合调用considerNotify(ObserverWrapper)

LiveData.considerNotify()

    private void considerNotify(ObserverWrapper observer) {
        if (!observer.mActive) {
            return;
        }
        if (!observer.shouldBeActive()) {
            observer.activeStateChanged(false);
            return;
        }
        if (observer.mLastVersion >= mVersion) {
            return;
        }
        observer.mLastVersion = mVersion;
        observer.mObserver.onChanged((T) mData);
    }

回调到Observer.onChanged()方法

LiveData还有异步线程更新数据的api

    contentLiveData.postValue("")
MutableLiveData.postValue()
    @Override
    public void postValue(T value) {
        super.postValue(value);
    }

LiveData.postValue()

    protected void postValue(T value) {
        boolean postTask;
        synchronized (mDataLock) {
            postTask = mPendingData == NOT_SET;
            mPendingData = value;
        }
        if (!postTask) {
            return;
        }
        ArchTaskExecutor.getInstance().postToMainThread(mPostValueRunnable);
    }

mPostValueRunnable

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

在Runnable中调用LiveData.setValue()

ArchTaskExecutor

public class ArchTaskExecutor extends TaskExecutor {
    public static ArchTaskExecutor getInstance() {
        if (sInstance != null) {
            return sInstance;
        }
        synchronized (ArchTaskExecutor.class) {
            if (sInstance == null) {
                sInstance = new ArchTaskExecutor();
            }
        }
        return sInstance;
    }

    private ArchTaskExecutor() {
        mDefaultTaskExecutor = new DefaultTaskExecutor();
        mDelegate = mDefaultTaskExecutor;
    }

    @Override
    public void postToMainThread(Runnable runnable) {
        mDelegate.postToMainThread(runnable);
    }
}

DefaultTaskExecutor.postToMainThread()

    @Override
    public void postToMainThread(Runnable runnable) {
        if (mMainHandler == null) {
            synchronized (mLock) {
                if (mMainHandler == null) {
                    mMainHandler = createAsync(Looper.getMainLooper());
                }
            }
        }
        mMainHandler.post(runnable);
    }

mMainHandler.post(runnable)

通过handler.post()切换到主线程执行

LiveData组件实现依赖于LifeCycle组件,分析完LifeCycle流程很容易理解其执行过程。