LiveData is an observable data holder class. Unlike a regular observable, LiveData is lifecycle-aware, meaning it respects the lifecycle of other app components, such as activities, fragments, or services. This awareness ensures LiveData only updates app component observers that are in an active lifecycle state.
一、LiveData是什么?
LiveData 是一种可观察的数据存储器类。
与常规的可观察类不同,LiveData 具有生命周期感知能力,意指它遵循其他应用组件(如 Activity、Fragment 或 Service)的生命周期。这种感知能力可确保 LiveData 仅更新处于活跃生命周期状态的应用组件观察者。
二、LiveData的优点
使用 LiveData 具有以下优势:
- 确保界面符合数据状态
LiveData 遵循观察者模式。当底层数据发生变化时,LiveData 会通知 Observer对象。您可以整合代码以在这些 Observer 对象中更新界面。这样一来,您无需在每次应用数据发生变化时更新界面,因为观察者会替您完成更新。
- 不会发生内存泄漏
观察者会绑定到Lifecycle对象,并在其关联的生命周期遭到销毁后进行自我清理。
- 不会因 Activity 停止而导致崩溃
如果观察者的生命周期处于非活跃状态(如返回栈中的Activity),则它不好接受任何LiveData事件
- 不再需要手动处理生命周期
界面组件只是观察相关数据,不会停止或恢复观察。LiveData 将自动管理所有这些操作,因为它在观察时可以感知相关的生命周期状态变化。
- 数据始终保持最新状态
如果生命周期变为非活跃状态,它会在再次变为活跃状态时接收最新的数据。例如,曾经在后台的 Activity 会在返回前台后立即接收最新的数据。
- 适当的配置更改
如果由于配置更改(如设备旋转)而重新创建了 Activity 或 Fragment,它会立即接收最新的可用数据。
- 共享资源
您可以使用单例模式扩展 LiveData对象以封装系统服务,以便在应用中共享它们。LiveData 对象连接到系统服务一次,然后需要相应资源的任何观察者只需观察 LiveData 对象。
三、使用 LiveData 对象
package com.anniljing.viewmodelcorestudy.liveData;
import android.os.Bundle;
import android.view.View;
import com.anniljing.viewmodelcorestudy.databinding.ActivityLiveDataBinding;
import java.util.Random;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.MutableLiveData;
public class LiveDataActivity extends AppCompatActivity {
private ActivityLiveDataBinding mBinding;
//声明可被观察的数据
private MutableLiveData<String> mLiveData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBinding = ActivityLiveDataBinding.inflate(getLayoutInflater());
setContentView(mBinding.getRoot());
//创建对象
mLiveData = new MutableLiveData<>();
//观察数据对象
mLiveData.observe(this, s -> {
mBinding.tvContent.setText(s);
});
}
public void operator(View view) {
//更新数据对象
mLiveData.setValue("" + (new Random().nextInt(100)));
}
}
四、源码分析
4.1、 MutableLiveData
public class MutableLiveData<T> extends LiveData<T> {
/**
* Creates a MutableLiveData initialized with the given {@code value}.
*
* @param value initial value
*/
public MutableLiveData(T value) {
super(value);
}
/**
* Creates a MutableLiveData with no value assigned to it.
*/
public MutableLiveData() {
super();
}
@Override
public void postValue(T value) {
super.postValue(value);
}
@Override
public void setValue(T value) {
super.setValue(value);
}
}
MutableLiveData只是继承了Livedata,具体的实现都是调用liveData父类的。
4.2、LiveData
4.2.1、构造方法
public LiveData(T value) {
mData = value;
mVersion = START_VERSION + 1;
}
public LiveData() {
mData = NOT_SET;
mVersion = START_VERSION;
}
如果创建对象的时候,传的有参数的话,则mVersion就会做加1的操作,mVersion的值在数据更新的时候,是否可以通知观察者。
4.2.2、订阅观察者
@MainThread
public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer) {
assertMainThread("observe");
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);
}
@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);
}
订阅观察者有两种实现,observe和observeForever,两者的区别在于内部wrapper的实现。
observe方法的wrapper是LifecycleBoundObserver
class LifecycleBoundObserver extends ObserverWrapper implements LifecycleEventObserver {
@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(@NonNull LifecycleOwner source,
@NonNull Lifecycle.Event event) {
Lifecycle.State currentState = mOwner.getLifecycle().getCurrentState();
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);
}
}
LifecycleBoundObserver实现了LifecycleEventObserver接口,onStateChanged方法里面,收到宿主的销毁的生命周期状态时,移除了相关的观察者,并且重写的shouldBeActive()方法也和宿主的生命周期同步。
observeForever方法的wrapper是AlwaysActiveObserver
private class AlwaysActiveObserver extends ObserverWrapper {
AlwaysActiveObserver(Observer<? super T> observer) {
super(observer);
}
@Override
boolean shouldBeActive() {
return true;
}
}
shouldBeActive方法的返回值是固定为true的,这样就会导致无论该数据依赖的宿主是否还存在,当数据有更新的时候,都会继续分发给已经可能销毁的宿主。
4.2.3、数据更新
数据更新liveData提供了两种方式,postValue和setValue,两者的区别在于处理数据的线程环境,postValue是在子线程中进行的,而setValue是在调用该方法时所在的当前线程环境。
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((T) newValue);
}
};
postValue方法最后把数据交给了mPostValueRunnable,mPostValueRunnable是一个子线程对象,在该线程的run方法里面调用了setValue()方法。
4.2.4、通知观察者
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;
}
private void considerNotify(ObserverWrapper observer) {
if (!observer.mActive) {
return;
}
if (!observer.shouldBeActive()) {
observer.activeStateChanged(false);
return;
}
if (observer.mLastVersion >= mVersion) {
return;
}
observer.mLastVersion = mVersion;
observer.mObserver.onChanged((T) mData);
}
在通知观察者之前,有三个判断来决定是否可以通知观察者,第一个是mActive的状态,第二个是shouldBeActive的状态,第三个是最后的版本与当前版本的大小关系。
4.2.4.1、mActive
void activeStateChanged(boolean newActive) {
if (newActive == mActive) {
return;
}
mActive = newActive;
changeActiveCounter(mActive ? 1 : -1);
if (mActive) {
dispatchingValue(this);
}
}
mActive的赋值是在activeStateChanged方法里面的,调用该方法的有两处,第一处是订阅观察者的wrapper的实现里面,observe的wrapper里面根据宿主的生命周期状态赋值,observeForever方法中直接赋值为true;第二个是移除观察者removeObserver,此时值为false。
4.2.4.2、shouldBeActive
oberve的wrapper里面,shouldBeActive的值是和宿主的生命周期状态绑定的
observeForever的wrapper里面,shouldBeActive的值固定为true。
4.2.4.3、mVersion
在setValue更新数据时,mVersion的值会进行++操作