概述
文章目录
- 前言
- 一、LiveData源码解析
- 二、实战细节
前言
这几天写项目遇到了关于LiveData的问题,就想记录下来,顺便解析一下LiveData
一、LiveData源码解析
1.LiveData为我们提供了对于数据的感知功能,能够在当数据改变的时候通过观察者模式去更新相应的数据。接下来我们来看一下源码:
public abstract class LiveData<T> {
@SuppressWarnings("WeakerAccess") /* synthetic access */
final Object mDataLock = new Object();
static final int START_VERSION = -1;
@SuppressWarnings("WeakerAccess") /* synthetic access */
static final Object NOT_SET = new Object();
//观察者集合
private SafeIterableMap<Observer<? super T>, ObserverWrapper> mObservers =
new SafeIterableMap<>();
// how many observers are in active state
@SuppressWarnings("WeakerAccess") /* synthetic access */
int mActiveCount = 0;
private volatile Object mData;
// when setData is called, we set the pending data and actual data swap happens on the main
// thread
@SuppressWarnings("WeakerAccess") /* synthetic access */
volatile Object mPendingData = NOT_SET;
//LiveData内部维护的版本号
private int mVersion;
private boolean mDispatchingValue;
@SuppressWarnings("FieldCanBeLocal")
private boolean mDispatchInvalidated;
private final Runnable mPostValueRunnable = new Runnable() {
@SuppressWarnings("unchecked")
@Override
public void run() {
Object newValue;
synchronized (mDataLock) {
newValue = mPendingData;
mPendingData = NOT_SET;
}
setValue((T) newValue);
}
};
/**
* Creates a LiveData initialized with the given {@code value}.
*
* @param value initial value
*/
public LiveData(T value) {
mData = value;
mVersion = START_VERSION + 1;
}
/**
* Creates a LiveData with no value assigned to it.
*/
public LiveData() {
mData = NOT_SET;
mVersion = START_VERSION;
}
从上面的代码可以看出,LiveData里面有一个Version字段,作为版本号,这个在更新的时候会有用到,然后里面有一个mObservers 的map集合。这个集合里面保存着所有对LiveData进行观察的观察者。
//这个方法就是会通知所有观察者
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;
}
//更新数据的秘密就在这里
@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);
}
注意:considerNotify方法中,当观察者不满足observer.mActive为真的时候,就会直接返回。
这个观察者就是我们使用LiveData添加观察者的时候来的,比如
viewModel.currentLanguage.observe(requireActivity(), androidx.lifecycle.Observer)
通过保存了观察者,并通过lifecycle时刻注意观察者的生命周期,当不处于活跃的时候,就不必要通知更新,这是很合理的做法。
那么我们如何判断哪些数据需要更新呢,那些不需要更新呢?这里我们回到刚刚说的Version字段,当我们观察者持有的Version>=当前LiveData的Version时,就不需要更新了。因为它就是最新的,当数据发生改变的时候,Version也会改变,从而在considerNotify中再次通知相关的观察者
@MainThread
protected void setValue(T value) {
assertMainThread("setValue");
mVersion++;
mData = value;
dispatchingValue(null);
}
/**
* Returns the current value.
* Note that calling this method on a background thread does not guarantee that the latest
* value set will be received.
*
* @return the current value
*/
@SuppressWarnings("unchecked")
@Nullable
public T getValue() {
Object data = mData;
if (data != NOT_SET) {
return (T) data;
}
return null;
}
看到这里我们明白了,当调用setValue的时候就会自动调用dispatchingValue进行对观察者们的通知,这就是为什么数值改变的时候会通知到观察者。
除了setValue(postValue本质也是调用了setValue,这里不分析)这个会调用dispatchingValue之外,还有一个也会调用到dispatchingValue函数,通知观察者
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;
}
// immediately set active state, so we'd never dispatch anything to inactive
// owner
mActive = newActive;
boolean wasInactive = LiveData.this.mActiveCount == 0;
LiveData.this.mActiveCount += mActive ? 1 : -1;
if (wasInactive && mActive) {
onActive();
}
if (LiveData.this.mActiveCount == 0 && !mActive) {
onInactive();
}
if (mActive) {
dispatchingValue(this);
}
}
ObserverWrapper 是对观察者的一层封装,当观察者的生命周期发生改变的时候,也会获取到最新的数值。activeStateChanged中可以看到,每一次生命周期改变,就会调用到这里,这就相当于对数据进行了一个粘性处理,即使时新建立的观察者,也能获取到当前最新的数据
二、实战细节
1.在实战中,有很多人会在viewmodel中直接调用XXLiveData.value去获取值,但是在viewmodel中,是不会对直接获取value的值做保证的,它会处于No-set状态,因此获取的值都是为Null。只有当value的值被改变的时候,通过观察者模式传递数据,才能保证获取到真实的值。
2.在我的一个项目中,有一个需求是利用page库和room配合,根据不同的参数返回不同的LiveData,但是我们又只能在观察者处观察一个LiveData。当LiveData本身被替换的时候,是不会触发数据更新的,从上文可以看到,只有里面的内容被改变,才会触发数据更新,因此需要对LiveData本身进行观察,可以用这个MutableLiveData里面嵌套LiveData的方式,去实现。
viewmodel中
var pageList=MutableLiveData<LiveData<PagedList<ItemData>>>()
pageList.value=wordRespository.getWordByType(currentid)
studyViewmodel.pageList.observe(requireActivity(), Observer {
it.observe(requireActivity(), Observer {
observe->
itemAdapter.submitList(observe)
})
最后
以上就是害怕山水为你收集整理的LiveData解析和项目遇到的问题记录前言一、LiveData源码解析二、实战细节的全部内容,希望文章能够帮你解决LiveData解析和项目遇到的问题记录前言一、LiveData源码解析二、实战细节所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复