jetpack系列—LiveData源码分析和实现事件分发总线

2021-03-18  本文已影响0人  Peakmain

使用

        mainViewModel = ViewModelProvider(this).get(MainViewModel::class.java)
        mainViewModel.text.observe(this, Observer {
        Log.e("TAG",it)
})
class MainViewModel:BaseViewModel() {
    private val _text = MutableLiveData<String>().apply {
        value = "This is MainViewModel"
    }
    val text: LiveData<String> = _text
}

源码分析

在源码分析之前我们首先来关注下ComponentActivity的源码

    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ReportFragment.injectIfNeededIn(this);
    }
public static void injectIfNeededIn(Activity activity) {
        if (Build.VERSION.SDK_INT >= 29) {
            // On API 29+, we can register for the correct Lifecycle callbacks directly
            activity.registerActivityLifecycleCallbacks(
                    new LifecycleCallbacks());
        }
        // use a framework fragment to get the correct timing of Lifecycle events
        android.app.FragmentManager manager = activity.getFragmentManager();
        if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
            manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
            // Hopefully, we are the first to make a transaction.
            manager.executePendingTransactions();
        }
    }

observe源码分析

    public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer) {
          //将owner和observer封装到LifecycleBoundObserver对象
        if (owner.getLifecycle().getCurrentState() == DESTROYED) {
            //如果是onDestory则直接return
            return;
        }
        //观察者和被观察者一起被封装到一个对象LifecycleBoundObserver中
        LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
          ObserverWrapper existing = mObservers.putIfAbsent(observer, wrapper);
       //代码省略
        owner.getLifecycle().addObserver(wrapper);
    }
 public void addObserver(@NonNull LifecycleObserver observer) {
         //此时的值实际是INITIALIZED
        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
        //将上面的LifecycleBoundObserver+状态封装成ObserverWithState
        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
       //代码省略
       //默认是false
        boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
        //代码省略
        if (!isReentrance) {
            // 第一次肯定会进入这里
            sync();
        }
        mAddingObserverCounter--;
    }
 private void sync() {
        //默认是true
        while (!isSynced()) {
        //代码省略
        }
        mNewEventOccurred = false;
    }

其实到这里所有的MainActivity的重写onCreate的代码已经执行完

setValue源码分析

       protected void setValue(T value) {
        assertMainThread("setValue");
        mVersion++;
        mData = value;
        dispatchingValue(null);
    }
    void dispatchingValue(@Nullable ObserverWrapper initiator) {
       //initiator=null
        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(); ) {
                   //value实际是我们将观察者和被观察者封装到一起的LifecycleBoundObserver 
                    considerNotify(iterator.next().getValue());
                    if (mDispatchInvalidated) {
                        break;
                    }
                }
            }
        } while (mDispatchInvalidated);
        mDispatchingValue = false;
    }
    private void considerNotify(ObserverWrapper observer) {
        if (!observer.mActive) {
            //判断是不是活动状态,实际是不是RESUMEND,如果是后台不发送
            return;
        } 
        if (!observer.shouldBeActive()) {
            observer.activeStateChanged(false);
            return;
        }
        if (observer.mLastVersion >= mVersion) {
            return;
        }
        observer.mLastVersion = mVersion;
           //调用被观察者的onChanged方法
        observer.mObserver.onChanged((T) mData);
    }

问题:为什么调用observer.mLastVersion >= mVersion进行判断?
假设现在有A和B两个Activity,现在A跳转到B Activity,那么此时A是不可见,B有个定时器,每隔一段时间对A数据进行更新,对于A来说,因为A是不可见的,所以我直接拒收你的消息,当更新一段时间后,返回到A Activity,其实A只需要显示最后一次更新的数据就好了。

源码分析总结

LiveData实现事件分发总线

object RxBus {
    private val eventMap = ConcurrentHashMap<String, StickyLiveData<*>>()

    /**
     * register bus
     */
    fun <T> register(eventName: String): StickyLiveData<T> {
        var liveData = eventMap[eventName]
        if (liveData == null) {
            liveData =
                StickyLiveData<T>(eventName)
            eventMap[eventName] = liveData
        }
        return liveData as StickyLiveData<T>
    }

    class StickyLiveData<T>(private val eventName: String) : LiveData<T>() {
        internal var mData: T? = null
        internal var mVersion = 0
        fun setData(data: T) {
            mData = data
            setValue(data)
        }

        fun postData(data: T) {
            mData = data
            postValue(data)
        }

        override fun setValue(value: T) {
            mVersion++
            super.setValue(value)
        }

        override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
            observerSticky(owner, false, observer)
        }

        fun observerSticky(owner: LifecycleOwner, sticky: Boolean, observer: Observer<in T>) {
            owner.lifecycle.addObserver(LifecycleEventObserver { source, event ->
                if (event == Lifecycle.Event.ON_DESTROY) {
                    eventMap.remove(eventName)
                }
            })
            super.observe(owner,
                StickyObserver(
                    this,
                    sticky,
                    observer
                )
            )
        }


    }

    /**
     * sticky不等于true,只能接收到注册之后发送的消息,如果想接受先发送后注册的消息需要设置sticky为true
     */
    class StickyObserver<T>(
        val stickyLiveData: StickyLiveData<T>,
        val sticky: Boolean,
        val observer: Observer<in T>
    ) : Observer<T> {
        private var lastVersion = stickyLiveData.mVersion
        override fun onChanged(t: T) {
            if (lastVersion >= stickyLiveData.mVersion) {
                if (sticky && stickyLiveData.mData != null) {
                   observer.onChanged(stickyLiveData.mData)
                }
                return
            }
            lastVersion=stickyLiveData.mVersion
            observer.onChanged(t)
        }


    }
}
上一篇下一篇

猜你喜欢

热点阅读