[Technology sharing] Livedata sticky event implements source code analysis, allowing you to fully grasp the data update mechanism

overview

Livedata sticky event is an observer pattern commonly used in Android, which allows the observer to be notified and the UI updated when the data changes. In actual development, we may encounter the situation of sticky events, that is, a piece of data is sent first, and then there are observers to listen. At this time, we need to ensure that the observer can receive the latest data. This article will analyze the principle of Livedata sticky events and the source code of Framework.

1. The principle of Livedata sticky event

When using Livedata, we can set the value of the data by calling the setValue method, and we can add observers through the observe method. If the setValue method has been called before the observer is added, then this data becomes a sticky event.

When an observer is added to Livedata, if Livedata already has data, the data will be sent to the observer immediately. And if there is no data, then the data will not be sent, and it will not be sent until the data of Livedata changes.

The principle of sticky events

In LiveData, if you use the setValue method, then when the Observer subscribes to the LiveData, the Observer will receive the latest update, however, if there is already an Observer subscribed to the LiveData before the setValue call, then it will not receive the update, This is called a "sticky event".

LiveData's sticky events are implemented through the internal mLastVersion counter. Whenever LiveData's setValue method is called, mVersion will increment by 1 and compare the current version number with mLastVersion. If the current version number is greater than mLastVersion, LiveData will notify all observers. If the current version number is less than or equal to mLastVersion , LiveData will not notify observers. When an observer subscribes to LiveData, LiveData assigns the current version number to the observer's version number, so that it can be determined whether the observer should receive the latest updated data.

Code sample for sticky events

The following is a code sample of Livedata sticky event:

kotlinCopy codeclass StickyLiveData<T> : MutableLiveData<T>() {
​
    private var stickyData: T? = null
​
    override fun setValue(value: T?) {
        stickyData = value
        super.setValue(value)
    }
​
    override fun postValue(value: T?) {
        stickyData = value
        super.postValue(value)
    }
​
    override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
        // 如果已经有粘性数据了,直接将它分发给观察者
        if (stickyData != null) {
            observer.onChanged(stickyData)
        }
        super.observe(owner, object : Observer<T> {
            override fun onChanged(t: T) {
                observer.onChanged(t)
            }
        })
    }
}

In this example, we create a StickyLiveData class that is a subclass of MutableLiveData. We override the setValue and postValue methods to handle sticky data. We also override the observe method to be able to distribute sticky data when there are observers subscribed to LiveData.

In the observe method, if sticky data exists, we distribute the sticky data to the new observer. We then pass the observer to the super.observe method so it can do regular observations on the LiveData.

Finally, when using the StickyLiveData class, you just need to subscribe to it like this:

kotlinCopy codestickyLiveData.observe(this, Observer {
    // 处理更新数据
})

This makes it possible to handle sticky data and distribute the latest data.

Two, Framework source code analysis

LiveData is an Android Architecture Component used to support observable data, which enables observers (such as Activity, Fragment, etc.) to automatically update the UI to reflect changes in the underlying data. In LiveData, an important concept is sticky event (Sticky Event), which allows observers to receive the latest data immediately when subscribing to LiveData.

The following is a brief analysis of LiveData source code:

LiveData is an observable data holder class with lifecycle awareness. When the data changes, it can notify all observers to perform update operations. LiveData has the following characteristics:

  1. Data holder: LiveData holds data and provides external access to data. LiveData supports generics and can contain any type of data.
  2. Observer mode: LiveData uses the observer mode, allowing multiple observers to observe the same LiveData object.
  3. Life cycle awareness: LiveData can sense the life cycle of components such as Activity and Fragment, so as to ensure that data updates are only performed when the components are activated.
  4. Sticky event: LiveData can store the latest data and send the latest data to the observer immediately when a new observer subscribes to LiveData.

The following is an example of the implementation principle of sticky events in the LiveData source code:

lessCopy codepublic class StickyLiveData<T> extends LiveData<T> {
    private T mStickyData;
​
    /**
     * 在setValue之前先把粘性事件的数据赋值给mStickyData
     */
    @Override
    public void setValue(T value) {
        mStickyData = value;
        super.setValue(value);
    }
​
    /**
     * 在observe时先判断mStickyData是否有值
     */
    @Override
    public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer) {
        if (mStickyData != null) {
            observer.onChanged(mStickyData);
        }
        super.observe(owner, observer);
    }
}

The above code shows how to implement the sticky event function in LiveData. In the setValue method, store the latest data in the mStickyData variable, and update the data to all observers by calling super.setValue(value). In the observe method, first judge whether mStickyData has a value, and if so, send it to the new observer immediately, so as to ensure that the observer can receive the latest data immediately.

The above is a brief analysis of the implementation principle of sticky events in the LiveData source code. In actual development, sticky events can help us better handle data update issues and improve application performance and user experience. More advanced learning of the Android framework; you can refer to the "Android Framework Family Bucket" document, which contains the underlying technology in the framework, communication, etc. covering 95%. Click to view detailed categories.

image.png

3. Summary

Livedata sticky event is a very practical observer mode, which can ensure that observers can receive the latest data. In actual development, we often encounter sticky events, so it is very important to understand its principle and source code implementation.

Guess you like

Origin blog.csdn.net/m0_71524094/article/details/130269993