LiveData
把ViewModel和LiveData与Act和Frg的生命周期关系理清楚就好了
ViewMode持有数据时长是高于Act/Frg的onDestroy()的,前两者就算执行到onDestroy()了,
vm里的数据也依然会存在一会,横竖屏切换就不用担心数据丢失
liveData回调数据往UI上显示的时候,也会观察Act/Frg生命周期
如果Acr/Frg被销毁,liveData是不会把数据往UI上回调,这个是防止内存泄漏
public void onStart() {
UserModel userModel = ViewModelProviders.of(getActivity()).get(UserModel.class);
}
创建
final UserModel viewModel = ViewModelProviders.of(this).get(UserModel.class);
ViewModelProviders创建一个ViewModelProvider
ViewModelProvider通过ViewModelStore保存了ViewModel,键值对的形式。
ViewModel是通过ViewModelProvider来实现缓存以及复用的。
ViewModelProvider.get创建或者得到ViewModel,会在Activity生命周期内创建
Activity,Fragment都有一个ViewModelStore,ViewModel会放进ViewModelStore中。
Activity,Fragmetn活动的时候,没有finish,没有killed,随着Activity和Fragment的生而生。因为是它的一个属性。
ViewModel就是一个普通的类,ViewModelProvider加了一层HashMap缓存来创建ViewModel,ViewModel跟随Activity消亡。
LiveData
@MainThread
public void observe(@NonNull LifecycleOwner owner, @NonNull Observer super T> observer) {
if (owner.getLifecycle().getCurrentState() == DESTROYED) {
// ignore
return;
}
LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
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;
}
owner.getLifecycle().addObserver(wrapper);
}
liveData监听Activity或者Fragment的生命周期,onStart或者onResume状态才会接收消息。
LifecycleOwner,Destroy时,observer自动被remove掉。
如果没有active,则不接收消息,如果重新active则接收最后一条消息。
一个LifecycleOwner只能添加一个observer。
class LifecycleBoundObserver extends ObserverWrapper implements GenericLifecycleObserver
final LifecycleOwner mOwner;
@Override
boolean shouldBeActive() {
return mOwner.getLifecycle().getCurrentState().isAtLeast(STARTED);
}
@Override
public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
if (mOwner.getLifecycle().getCurrentState() == DESTROYED) {
removeObserver(mObserver);
return;
}
activeStateChanged(shouldBeActive());
}
@Override
boolean isAttachedTo(LifecycleOwner owner) {
return mOwner == owner;
}
@Override
void detachObserver() {
mOwner.getLifecycle().removeObserver(this);
}
private abstract class ObserverWrapper {
final Observer super T> mObserver;
boolean mActive;
int mLastVersion = START_VERSION;
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);
}
}
}
@MainThread
protected void setValue(T value) {
assertMainThread("setValue");
mVersion++;
mData = value;
dispatchingValue(null);
}
最终调用了dispatchingValue(value),version++。version很重要,在发送数据改变时会判断会不会发送出去。
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, ObserverWrapper>> iterator =
mObservers.iteratorWithAdditions(); iterator.hasNext(); ) {
considerNotify(iterator.next().getValue());
if (mDispatchInvalidated) {
break;
}
}
}
} while (mDispatchInvalidated);
mDispatchingValue = false;
}
LiveData持有LifecycleOwner,可以根据生命周期的状态决定要不要发送事件。也是面向接口编程。发送数据时,考虑生命周期,考虑发送次数,不是active,只发送最后一条信息。