jetpack之LiveData的源码解读

源码版本:Android 10

一、LiveData基本使用方法

package com.study.jetpackstudykotlin


import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
	//MutableLiveData是LiveData的子类
    val mutableLiveData = MutableLiveData<String>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        lifecycle.addObserver(MainActivityLifeObserver())
        tv_exit.setOnClickListener {
            mutableLiveData.value = "jetpack"
        }

        mutableLiveData.observe(this, object : Observer<String> {
            override fun onChanged(t: String?) {
                t?.apply {
                    Log.e("Observer==", "MutableLiveData====${t}")
                }
            }
        })
    }
}

二、LiveData源码分析

2.1 给LiveData添加观察者

mutableLiveData.observe()添加观察者,LiveData的observe源码如下:
 public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer) {
        //线程检查
        assertMainThread("observe");
        if (owner.getLifecycle().getCurrentState() == DESTROYED) {
            // ignore
            return;
        }
        //封装Observer
        LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
        //保存Observer
        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;
        }
        //将封装之后的观察者传递给Actvity以实现,Observer与Activity实例相绑定
        owner.getLifecycle().addObserver(wrapper);
}

owner.getLifecycle().addObserver(wrapper)方法所走逻辑大家可以看jetpack之Lifecycle的源码解读,要注意在Lifecycling.getCallback(observer)走的是if (object instanceof GenericLifecycleObserver) 分支

2.2 处理Activity生命周期事件

observer.dispatchEvent最终调用的是LiveData.LifecycleBoundObserver中的onStateChanged方法,LifecycleBoundObserver源码如下所示:
    class LifecycleBoundObserver extends ObserverWrapper implements GenericLifecycleObserver {
        @NonNull
        final LifecycleOwner mOwner;

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

        //当前Activity实例生命周期事件应该大于等于STARTED,大于时返回true,否则返回false
        @Override
        boolean shouldBeActive() {
            return mOwner.getLifecycle().getCurrentState().isAtLeast(STARTED);
        }

        //当前实例所在Activity周期发生变化的时候调用
        @Override
        public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
        //当前什么生命周期的事件等于DESTROYED时,移除当前实例并返回
            if (mOwner.getLifecycle().getCurrentState() == DESTROYED) {
                removeObserver(mObserver);
                return;
            }
            activeStateChanged(shouldBeActive());
        }

        //判断当前实例是否添加在当前Activity实例上
        @Override
        boolean isAttachedTo(LifecycleOwner owner) {
            return mOwner == owner;
        }

        //从当前Activity实例中移除当前实例
        @Override
        void detachObserver() {
            mOwner.getLifecycle().removeObserver(this);
        }
    }

    private abstract class ObserverWrapper {
        final Observer<? super T> mObserver;
        boolean mActive;
        int mLastVersion = START_VERSION;

        ObserverWrapper(Observer<? super T> observer) {
            mObserver = observer;
        }

        abstract boolean shouldBeActive();

        boolean isAttachedTo(LifecycleOwner owner) {
            return false;
        }

        void detachObserver() {
        }

        void activeStateChanged(boolean newActive) {
            if (newActive == mActive) {
                return;
            }
            // 这部分源码在自己继承LiveData及其子类时调用
            mActive = newActive;
            boolean wasInactive = LiveData.this.mActiveCount == 0;
            LiveData.this.mActiveCount += mActive ? 1 : -1;
            if (wasInactive && mActive) {
                onActive();  //LiveData对其是空实现
            }
            if (LiveData.this.mActiveCount == 0 && !mActive) {
                onInactive(); //LiveData对其是空实现
            }
            if (mActive) {
                dispatchingValue(this); //分发值
            }
        }
    }

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 {
                //轮询通知当前LiveData添加的所有Observer
                for (Iterator<Map.Entry<Observer<? super T>, ObserverWrapper>> iterator =
                        mObservers.iteratorWithAdditions(); iterator.hasNext(); ) {
                    considerNotify(iterator.next().getValue());
                    if (mDispatchInvalidated) {
                        break;
                    }
                }
            }
        } while (mDispatchInvalidated);
        mDispatchingValue = false;
    }

    private void considerNotify(ObserverWrapper observer) {
        if (!observer.mActive) {
            return;
        }
       
        //检查observer最新的状态
        if (!observer.shouldBeActive()) {
            observer.activeStateChanged(false);
            return;
        }
        //判断observer版本,此处也是修改LiveData粘性事件的关键点
        if (observer.mLastVersion >= mVersion) {
            return;
        }
        observer.mLastVersion = mVersion;
        //通知LiveData添加的observer
        observer.mObserver.onChanged((T) mData);
    }

2.3 LiveData发送数据源码分析

mutableLiveData.value = "jetpack"源码如下所示:
protected void setValue(T value) {
        //检查是否在主线程中调用
        assertMainThread("setValue");
        //版本加1
        mVersion++;
        //赋值
        mData = value;
        //分发值
        dispatchingValue(null);
}

三、总结

这里只拿LiveData的setValue方法进行了分析,只是个人对LiveData源码的解读,如有不足之处敬请指出。

LiveData时序图

你可能感兴趣的:(Android技巧-源码分析)