liveData使用
使用1
先注册监听,然后postValue
liveData.observe(this, new Observer<String>() {
@Override
public void onChanged(String s) {
Toast.makeText(LoginActivity.this,s,Toast.LENGTH_SHORT).show();
}
});
public void postValue(View view) {
liveData.postValue("liveData");
}
使用2 (不建议使用)
先postValue,然后注册监听。
应用场景,ActivityA --->ActivityB,在A中postValue,在B中注册监听,接受数据,这和一般的观察者模式不太一样,稍后会源码分析。但不建议这么使用,可能会遇到一下奇奇怪怪的问题。
使用3:LiveDataBus
以上两种都是一个liveData,传递一个数据。在App中,我们会需要传递很多数据,一个liveData像一个传递数据的管道,但每个管道只能传递一个数据,每次传递新数据,都要新建管道。所以需要一个管道集和,来对这些管道进行管理。这就是LiveData,管理一个存储LiveData的HashMap。
因为常常英语组件间通信,所以LiveData创建在BaseModule,并且是个单例。
下篇文章讲解。
源码分析 postValue
postValue
protected void postValue(T value) {
boolean postTask;
synchronized (mDataLock) {
postTask = mPendingData == NOT_SET;
mPendingData = value; ---1
}
if (!postTask) {
return; ---3
}
ArchTaskExecutor.getInstance().postToMainThread(mPostValueRunnable); --2
}
发送消息还有个setValue,区别是setValue只能在主线程发消息,postValue都可以,setValue一会会遇到。
- 1,会把 value放到 临时变量 mPendingData
- 2,通过handler切换到主线程执行runnable
- 3,这里可以处理button快速点击之类的问题,mPendingData 的初始值是NOT_SET,当前消息处理完,还会设为NOT_SET。所以 如果postTask为false,说明前一个消息还没处理完,当前消息return,防止快速点击。
接着看 runnable
private final Runnable mPostValueRunnable = new Runnable() {
@Override
public void run() {
Object newValue;
synchronized (mDataLock) {
newValue = mPendingData;---1
mPendingData = NOT_SET;---2
}
//noinspection unchecked
setValue((T) newValue);---3
}
};
- 1,value 赋值给了 newValue,
- 2,mPendingData 重置了
- 3,看到上面说的setValue
setValue
protected void setValue(T value) {
assertMainThread("setValue");---1
mVersion++;---2
mData = value;---3
dispatchingValue(null);
}
- 1,setValue 必须在主线程
- 2,以后分析 会用到(先postValue 后 addObserver)
- 3,赋值mData,mData就是 Observer获取的值
dispatchingValue
void dispatchingValue(@Nullable ObserverWrapper initiator) {
if (mDispatchingValue) {
mDispatchInvalidated = true;
return;
}
mDispatchingValue = true;
do { ---1,
mDispatchInvalidated = false;
if (initiator != null) { ---2
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;
}
- 1,这一部分是重点,意思是取出每一个观察者。接下来considerNotify
mObservers是怎么添加的,后面分析添加观察者会讲到。 - 2,这里的入参initiator == null,所以走else部分
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 better not
// notify for a more predictable notification order.
if (!observer.shouldBeActive()) {
observer.activeStateChanged(false); ---1
return;
}
if (observer.mLastVersion >= mVersion) {---2
return;
}
observer.mLastVersion = mVersion;
//noinspection unchecked
observer.mObserver.onChanged((T) mData);---3
}
1,2 部分先不管,直接3部分
Observer.onChanged
public interface Observer<T> {
/**
* Called when the data is changed.
* @param t The new data
*/
void onChanged(T t);
}
这就是创建的监听者的回调。
现在回过头,看一下mObservers是怎么添加的。
源码分析 observe
observe
public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer) {
assertMainThread("observe");
if (owner.getLifecycle().getCurrentState() == DESTROYED) {---1
// ignore
return;
}
LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
ObserverWrapper existing = mObservers.putIfAbsent(observer, wrapper);---2
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);---3
}
- 1,和生命周期绑定,如果destroy,则不监听
- 2,mObservers 集和 添加。其实到此为止,和生命周期没什么关系,就是一个简单的观察者/监听事件。牛逼的是最后一行。
- 3,LifecycleBoundObserver(看名字 就知道 很不一般) 。为生命周期增加观察者,
class LifecycleBoundObserver extends ObserverWrapper implements GenericLifecycleObserver {
@NonNull
final LifecycleOwner mOwner;
LifecycleBoundObserver(@NonNull LifecycleOwner owner, Observer<? super T> observer) {
super(observer);
mOwner = owner;
}
@Override
boolean shouldBeActive() {
return mOwner.getLifecycle().getCurrentState().isAtLeast(STARTED);
}
@Override
public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) { ---1
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);
}
}
- 1,生命周期改变,会走这里 onStateChanged
更改顺序,先postValue,后observe 会怎么样。
owner.getLifecycle().addObserver(wrapper);
这里就是LiveData和一般的观察者,EventBus不同的地方。通过这个
方法监听了android组件的生命周期。在生命周期变化时,回调onStateChanged方法。这就是先post 然后observe也能监听的原因。接下来 具体分析:
@Override
public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) { ---1
if (mOwner.getLifecycle().getCurrentState() == DESTROYED) {
removeObserver(mObserver); ---1
return;
}
activeStateChanged(shouldBeActive());
}
- 1,监听者销毁时,取消监听。liveData的优点
activeStateChanged
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);---1
}
}
- 1,setValue最终也走到这个方法,这就找到了共同点。不同的是这里参数不是null。在setValue中参数是null。
再看一下dispatchingValue
dispatchingValue
void dispatchingValue(@Nullable ObserverWrapper initiator) {
if (mDispatchingValue) {
mDispatchInvalidated = true;
return;
}
mDispatchingValue = true;
do {
mDispatchInvalidated = false;
if (initiator != null) {
considerNotify(initiator);---1,
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;
}
- 1,参数不是null,所i有走这个if分支,直接回调观察者的onChanged()
有个问题,既然onStateChange会在生命周期改变的时候回调,那么在create、start、resume都会回调,但为什么实际效果,onChange只执行了一次??
答案在considerNotify()
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 better not
// notify for a more predictable notification order.
if (!observer.shouldBeActive()) {
observer.activeStateChanged(false);
return;
}
if (observer.mLastVersion >= mVersion) { ---1
return;
}
observer.mLastVersion = mVersion;---2
//noinspection unchecked
observer.mObserver.onChanged((T) mData);
}
- 1,mLastVersion 和mVersion的初始值都是-1。画个表格吧
总结:post之后,同一个观察值,只能执行一次