什么是LiveData
它可以用来持有 可被观察的数据,可以感知到UI组件的生命周期,只有组件处于活动(STARTED和RESUMED)状态时,LivedData才可以用来更新数据。当组件DESTROYED的时候,它会自动移出,不会引起内存泄露
关注以下几个类
- LiveData
ObserverWrapper
LifecycleBoundObserver: (实现GenericLifecycleObserver接口) - GenericLifecycleObserver: 一个接口,感知组件生命周期的变化,通知给观察者
- LifecycleRegistry (Lifecycle的子类)
Demo
public class NameViewModel extends ViewModel {
//MutableLiveData 是LiveDaTa的子类
private MutableLiveData<String> mCurrentName;
public MutableLiveData<String> getCurrentName() {
if(mCurrentName==null){
mCurrentName = new MutableLiveData<>();
}
return mCurrentName;
}
}
public class NameActvity extends AppCompatActivity {
private NameViewModel mModel;
private TextView mNameTv;
private Button mBtn;
private String[] names = {"张三", "李四", "王麻子"};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_name);
mNameTv = (TextView) findViewById(R.id.nameTv);
mBtn = (Button) findViewById(R.id.btn);
//1. 通过反射获得NameViewModel,不关注这个
mModel = ViewModelProviders.of(this).get(NameViewModel.class);
//2. 实现观察者(lifecycle包下的接口)
Observer<String> nameObserver = new Observer<String>() {
//每次数据更新都会自动回调
@Override
public void onChanged(@Nullable String s) {
mNameTv.setText(s);
}
};
//3.为LiveData添加观察者
重点看这里(组件必须实现了LifecycleOwner ,所以LivdeData还是要结合Lifecycle使用),进入源码
mModel.getCurrentName().observe(this, nameObserver);
mBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int random = (int) (Math.random() * 3);
String name = names[random];
//4.推送信息(只能在主线程,其他用postValue())
mModel.getCurrentName().setValue(name);
}
});
}
}
源码
LiveData
@MainThread
public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer) {
//组件当前状态为DESTROYED,不添加观察者
if (owner.getLifecycle().getCurrentState() == DESTROYED) {
// ignore
return;
}
//LifecycleBoundObserver 是ObserverWrapper 的包装类
LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
//以observer为key,wrapper为value关联存入,如果之前有关联直接返回wrapper,如果没有,存入且返回Null,
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;
}
最终是通过Lifecycle来添加观察者
进入LifecycleRegistry
owner.getLifecycle().addObserver(wrapper);
}
LifecycleRegistry
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
//添加观察者的时候只区分两种状态 不是销毁 就是 新生
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
//如果之前添加过,就结束
if (previous != null) {
return;
}
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
//如果组件生命周期结束,就结束
if (lifecycleOwner == null) {
// it is null we should be destroyed. Fallback quickly
return;
}
boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
//计算目标观察者的状态
State targetState = calculateTargetState(observer);
//添加的过观察者计数器
mAddingObserverCounter++;
while ((statefulObserver.mState.compareTo(targetState) < 0
&& mObserverMap.contains(observer))) {
pushParentState(statefulObserver.mState);
分发事件
statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));
popParentState();
// mState / subling may have been changed recalculate
targetState = calculateTargetState(observer);
}
if (!isReentrance) {
// we do sync only on the top level.
sync();
}
mAddingObserverCounter--;
}
分发事件
LifecycleRegistry->ObserverWithState
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
生命周期状态改变的回调
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
生命周期状态改变的回调
LiveData->LifecycleBoundObserver
@Override
public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
if (mOwner.getLifecycle().getCurrentState() == DESTROYED) {
removeObserver(mObserver);
return;
}
活动状态改变的回调
activeStateChanged(shouldBeActive());
}
活动状态改变的回调
LiveData->ObserverWrapper
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) {
传递 ObserverWrapper
dispatchingValue(this);
}
}
传递ObserverWrapper
LiveData
private 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<T>, ObserverWrapper>> iterator =
mObservers.iteratorWithAdditions(); iterator.hasNext(); ) {
推送数据
considerNotify(iterator.next().getValue());
if (mDispatchInvalidated) {
break;
}
}
}
} while (mDispatchInvalidated);
mDispatchingValue = false;
}
推送数据 LiveData
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;
//noinspection unchecked
观察者获得数据
observer.mObserver.onChanged((T) mData);
}