LiveData 为什么会初始化?
问题:
为什么有的时候在进入一些页面的时候,livedata.observe{ 这里的代码会执行 }?
LiveData源码解析
- setValue
@MainThread
protected void setValue(T value) {
assertMainThread("setValue");
mVersion++; //注意这个
mData = value;
dispatchingValue(null);
}
- dispatchingValue
//省略
considerNotify(iterator.next().getValue());
//省略
- considerNotify
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

本文探讨了Android LiveData在何时会进行初始化的问题。当进入页面并使用LiveData的observe方法时,内部的源码解析显示,如果LiveData之前调用了setValue,那么observe的回调会执行,即会发生初始化。反之,如果没有调用setValue,observe则不会触发初始化。总结来说,LiveData的初始化行为取决于它是否已被setValue触发。
最低0.47元/天 解锁文章
1904

被折叠的 条评论
为什么被折叠?



