JetPack系列(二)LiveData
LiveData 简介
LiveData是一个可观察的数据持有者类,与常规的Observable不同,LiveData可感知Activity、Fragment、Service的生命周期,确保LiveData仅更新处于活动生命周期状态的组件观察者。如果应用程序组件观察者处于started
或者resumed
,则LiveData认为该组件处于活跃状态,该组件会收到LiveData的数据更新,而其他注册的组件观察者将不会收到任何数据更新。
主要方法
observe(LifecycleOwner owner, Observer observer)//注册和宿主生命周期关联的观察者
observeForever(Observer observer)//注册观察者,不会反注册,需自行维护
setValue(T data)//发送数据,没有活跃的观察者时不分发,只能在主线程使用
postValue(T data)//和setValue一样,不受线程环境限制
onActive//当且仅当有一个活跃的观察者时触发
inActive//不存在活跃的观察者时会触发
MutableLiveData
MutableLiveData是LiveData的实现类,其主要功能是将setValue和postValue两个方法变成public以供外部调用,这样做的好处是防止拿到LiveData即可以发消息又可以收消息,开闭原则。
public class MutableLiveData<T> extends LiveData<T> {
public MutableLiveData(T value) {
super(value);
}
public MutableLiveData() {
super();
}
@Override
public void postValue(T value) {
super.postValue(value);
}
@Override
public void setValue(T value) {
super.setValue(value);
}
}
MutableLiveData使用比较简单,只要设置宿主和观察者。调用postValue和setValue就可以发送消息
```
class LiveDataTestActivity : AppCompatActivity(){
private val TAG = "LiveDataTestActivity";
val mutableLiveData : MutableLiveData<String> = MutableLiveData()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.frament_test)
mutableLiveData.observe(this, Observer {
Log.e(TAG, "onCreate$it")
})
mutableLiveData3.value = "liveDataMap";
}
} ```
MediatorLiveData
MediatorLiveData可以观察多个LiveData,允许多个LiveData合并发射到同一个对象中。
通过addSource将多个LiveData合并到一起,在LiveData数据发生改变后通过MediatorLiveData#setValue()或MediatorLiveData#postValue()将所有数据发送到MediatorLiveData上
```
class LiveDataTestActivity : AppCompatActivity(){
private val TAG = "LiveDataTestActivity";
val mutableLiveData1 : MutableLiveData
mediatorLiveData.observe(this, Observer {
Log.e(TAG, "mediatorLiveData${System.currentTimeMillis()}")
Log.e(TAG, "$it---${Thread.currentThread()}")
})
}
} ```
Transformations.map
Transformations.map可以将LiveData发送过来的数据进行转换
从源码中看到Transformations.map创建了一个MediatorLiveData,并将原先的LiveData通过addSource放入,在数据发生改变时调用result.setValue(mapFunction.apply(x));将数据转换并发送(由于转换时在onChanged方法上调用所以转换发生在主线程上)
@MainThread
@NonNull
public static <X, Y> LiveData<Y> map(
@NonNull LiveData<X> source,
@NonNull final Function<X, Y> mapFunction) {
final MediatorLiveData<Y> result = new MediatorLiveData<>();
result.addSource(source, new Observer<X>() {
@Override
public void onChanged(@Nullable X x) {
result.setValue(mapFunction.apply(x));
}
});
return result;
}
val liveDataMap :LiveData<Int> = Transformations.map(mutableLiveData3
) {
Log.d(TAG, Thread.currentThread().name)
1
}
liveDataMap.observe(this, Observer {
Log.d("", "");
})
mutableLiveData3.postValue("3")
源码分析以及黏性事件
observe方法解析
@MainThread
public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer) {
//observe必须在主线程时调用
assertMainThread("observe");
//如果在宿主生命周期为DESTROYED时调用则忽略这个观察者
if (owner.getLifecycle().getCurrentState() == DESTROYED) {
// ignore
return;
}
//将观察者包装成LifecycleBoundObserver
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;
}
//将观察者注册到宿主的Lifecycle中
owner.getLifecycle().addObserver(wrapper);
}
LifecycleBoundObserver解析
```
class LifecycleBoundObserver extends ObserverWrapper implements LifecycleEventObserver {
@NonNull
final LifecycleOwner mOwner;
LifecycleBoundObserver(@NonNull LifecycleOwner owner, Observer<? super T> observer) {
super(observer);
mOwner = owner;
}
//检测宿主是否处于活跃状态,在STARTED之后的状态为活跃状态
@Override
boolean shouldBeActive() {
return mOwner.getLifecycle().getCurrentState().isAtLeast(STARTED);
}
//当宿主的生命周期发生变化时调用此方法
@Override
public void onStateChanged(@NonNull LifecycleOwner source,
@NonNull Lifecycle.Event event) {
Lifecycle.State currentState = mOwner.getLifecycle().getCurrentState();
//如果宿主的生命周期进入DESTROYED则移除这个观察者
if (currentState == DESTROYED) {
removeObserver(mObserver);
return;
}
//同步观察者到宿主的生命周期状态
Lifecycle.State prevState = null;
while (prevState != currentState) {
prevState = currentState;
activeStateChanged(shouldBeActive());
currentState = mOwner.getLifecycle().getCurrentState();
}
}
@Override
boolean isAttachedTo(LifecycleOwner owner) {
return mOwner == owner;
}
@Override
void detachObserver() {
mOwner.getLifecycle().removeObserver(this);
}
}
ObserverWrapper解析
private abstract class ObserverWrapper {
final Observer<? super T> mObserver;
//是否活跃
boolean mActive;
int mLastVersion = START_VERSION;
ObserverWrapper(Observer<? super T> observer) {
mObserver = observer;
}
abstract boolean shouldBeActive();
boolean isAttachedTo(LifecycleOwner owner) {
return false;
}
void detachObserver() {
}
//宿主的生命周期变化将会调用次方法
void activeStateChanged(boolean newActive) {
//如果从活跃状态到活跃状态则直接返回
//只有从活跃状态变为不活跃,或不活跃变为活跃状态才会走下面的代码
if (newActive == mActive) {
return;
}
// immediately set active state, so we'd never dispatch anything to inactive
// owner
mActive = newActive;
//记录观察者的数量,如果活跃状态,观察者+1,如果不活跃,观察者-1
changeActiveCounter(mActive ? 1 : -1);
//如果是活跃状态,分发消息
if (mActive) {
dispatchingValue(this);
}
}
}
changeActiveCounter 方法解析
@MainThread
void changeActiveCounter(int change) {
//记录当前的观察者数量
int previousActiveCount = mActiveCount;
//生命周期变化后的观察者数量
mActiveCount += change;
//记录修改状态,进入该方法mChangingActiveState为true,结束该方法mChangingActiveState为false
if (mChangingActiveState) {
return;
}
mChangingActiveState = true;
try {
while (previousActiveCount != mActiveCount) {
//当前的观察者数量为0,且更新后观察者数量大于0,表示第一个观察者活跃起来
boolean needToCallActive = previousActiveCount == 0 && mActiveCount > 0;
//当前观察者数量大约0,且宿主生命周期变化后观察者数量等于0表示所有观察者都将不活跃
boolean needToCallInactive = previousActiveCount > 0 && mActiveCount == 0;
previousActiveCount = mActiveCount;
if (needToCallActive) {
//第一个观察者活跃起来调用方法
onActive();
} else if (needToCallInactive) {
//没有活跃的观察者调用该方法
onInactive();
}
}
} finally {
mChangingActiveState = false;
}
}
dispatchingValue方法解析
//当调用setValue或postValue的时候initiator为空,生命周期变化导致进入该方法initiator不为空
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<? super T>, ObserverWrapper>> iterator =
mObservers.iteratorWithAdditions(); iterator.hasNext(); ) {
considerNotify(iterator.next().getValue());
if (mDispatchInvalidated) {
break;
}
}
}
} while (mDispatchInvalidated);
mDispatchingValue = false;
}
considerNotify方法解析
@SuppressWarnings("unchecked")
private void considerNotify(ObserverWrapper observer) {
//观察者不活跃直接退出
if (!observer.mActive) {
return;
}
if (!observer.shouldBeActive()) {
observer.activeStateChanged(false);
return;
}
//最后一个消息版本和现在的消息版本一致则推出
//因为生命周期改变或者添加新的观察者也会进入到该方法,所以需要增加判断
//这行代码也是黏性事件的原因,当观察者刚注册进来,mLastVersion为0,此时如果LiveData发送过消息
//则mVersion不为0,此时会把最后一条消息分发出去
//如果观察者在不活跃状态变为活跃状态,也只能收到最后一条消息
if (observer.mLastVersion >= mVersion) {
return;
}
//将观察者版本同步到LiveData版本,防止消息重复发送
observer.mLastVersion = mVersion;
//分发消息
observer.mObserver.onChanged((T) mData);
}
setValue
@MainThread
protected void setValue(T value) {
assertMainThread("setValue");
//消息版本+1
mVersion++;
mData = value;
分发消息
dispatchingValue(null);
}
postValue
protected void postValue(T value) {
boolean postTask;
synchronized (mDataLock) {
postTask = mPendingData == NOT_SET;
mPendingData = value;
}
if (!postTask) {
return;
}
//将发送操作放到Handler上发送到主线程
ArchTaskExecutor.getInstance().postToMainThread(mPostValueRunnable);
}
observeForever解析
@MainThread
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);
}
private class AlwaysActiveObserver extends ObserverWrapper {
AlwaysActiveObserver(Observer<? super T> observer) {
super(observer);
}
//观察者永远处于活跃状态
@Override
boolean shouldBeActive() {
return true;
}
}
static void assertMainThread(String methodName) { if (!ArchTaskExecutor.getInstance().isMainThread()) { throw new IllegalStateException("Cannot invoke " + methodName + " on a background" + " thread"); } } ```