LifeCycle : 绑定了activity的生命周期,通过注册观察者,可以用来监听activity 的生命周期变化
lifecycle 的拥有者
public interface LifecycleOwner {
/**
* Returns the Lifecycle of the provider.
*
* @return The lifecycle of the provider.
*/
@NonNull
Lifecycle getLifecycle();
}
lifecycle 扩展类: 用来给观察者分发生命 生命周期回调
public class LifecycleRegistry extends Lifecycle {
...
}
activity 默认实现了接口(lifeCycle的拥有者),提供了一个lifeCycle 实例
public class ComponentActivity extends Activity implements
LifecycleOwner,
KeyEventDispatcher.Component {
...
}
public class FragmentActivity extends ComponentActivity{
//默认创建lifeCycle
final LifecycleRegistry mFragmentLifecycleRegistry = new LifecycleRegistry(this);
//分发onCreate 事件
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
...
mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
}
//分发onStart
@Override
protected void onStart() {
super.onStart();
...
mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
}
//分发onResume
protected void onResumeFragments() {
mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
mFragments.dispatchResume();
}
}
//分发onPause
@Override
protected void onPause() {
super.onPause();
...
mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE);
}
//分发 onStop
...
//分发onDestory
...
//新建观察者
private LifecycleObserver lifecycleEventObserver=new LifecycleEventObserver(){
/**
* Called when a state transition event happens.
*
* @param source The source of the event
* @param event The event
*/
@Override
public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
}
};
//注册
getLifecycle().addObserver(lifecycleEventObserver);
//移除
getLifecycle().removeObserver(lifecycleEventObserver);
1.可以注册观察者
2.持有LifeCycleOwer 引用用,当LifeCycle 处于活跃状态时(Lifecycle.State#STARTED or @link Lifecycle.State#RESUMED),才会通知观察者
3.被设计和ViewModel 一起使用。
@MainThread
public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer) {
//检查是否为主线程
assertMainThread("observe");
//当ower 处于的destory 状态
if (owner.getLifecycle().getCurrentState() == DESTROYED) {
// ignore
return;
}
//LifecycleEventObserver 装饰类
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;
}
//给ower 注册生命周期回调
owner.getLifecycle().addObserver(wrapper);
}
//不绑定生命周期,会一直收到变化消息
public void observeForever(@NonNull Observer<? super T> observer) {
assertMainThread("observeForever");
AlwaysActiveObserver wrapper = new AlwaysActiveObserver(observer);
ObserverWrapper existing = mObservers.putIfAbsent(observer, wrapper);
if (existing instanceof LiveData.LifecycleBoundObserver) {
throw new IllegalArgumentException("Cannot add the same observer"
+ " with different lifecycles");
}
if (existing != null) {
return;
}
wrapper.activeStateChanged(true);
}
在主线程设置数据
@MainThread
protected void setValue(T value) {
assertMainThread("setValue");
mVersion++;
mData = value;
dispatchingValue(null);
}
//分发data
void dispatchingValue(@Nullable ObserverWrapper initiator) {
if (mDispatchingValue) {
mDispatchInvalidated = true;
return;
}
mDispatchingValue = true;
do {
mDispatchInvalidated = false;
if (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;
}
//通知观察者
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);
}
在任何线程使用
protected void postValue(T value) {
boolean postTask;
synchronized (mDataLock) {
postTask = mPendingData == NOT_SET;
mPendingData = value;
}
if (!postTask) {
return;
}
//发送到主线程
ArchTaskExecutor.getInstance().postToMainThread(mPostValueRunnable);
}
private final Runnable mPostValueRunnable = new Runnable() {
@SuppressWarnings("unchecked")
@Override
public void run() {
Object newValue;
synchronized (mDataLock) {
newValue = mPendingData;
mPendingData = NOT_SET;
}
//执行setValue()
setValue((T) newValue);
}
};
//移除管理ower的所有观察者
@MainThread
public void removeObservers(@NonNull final LifecycleOwner owner) {
assertMainThread("removeObservers");
for (Map.Entry<Observer<? super T>, ObserverWrapper> entry : mObservers) {
if (entry.getValue().isAttachedTo(owner)) {
removeObserver(entry.getKey());
}
}
}
@MainThread
public void removeObserver(@NonNull final Observer<? super T> observer) {
assertMainThread("removeObserver");
ObserverWrapper removed = mObservers.remove(observer);
if (removed == null) {
return;
}
removed.detachObserver();
removed.activeStateChanged(false);
}
public class SharedViewModel extends ViewModel {
//创建liveData
private final MutableLiveData<Student> studentMutableLiveData=new MutableLiveData<>();
public MutableLiveData<Student> getStudentMutableLiveData() {
return studentMutableLiveData;
}
//ViewModel 清除时回调
@Override
protected void onCleared() {
super.onCleared();
}
}
SharedViewModel sharedViewModel = new ViewModelProvider(this).get(SharedViewModel.class);
sharedViewModel.getStudentMutableLiveData().observe(this, new Observer<Student>() {
@Override
public void onChanged(Student student) {
}
});
sharedViewModel.getStudentMutableLiveData().setValue(...);
sharedViewModel.getStudentMutableLiveData().postValue(...);
注意: