简介
LiveData是可观察的数据持有者类
用法
- 定义LiveDatas数据
class LiveDataMode{
val currentName: MutableLiveData<String> by lazy { MutableLiveData<String>() }
}
- 使用
private fun useLiveData(){
val mode = LiveDataMode()
val nameObserver = Observer<String> { newName ->
Log.e(TAG,"new name $newName")
}
// 添加数据观察
mode.currentName.observe(this, nameObserver)
// 改变值
mode.currentName.postValue("丘比特")
}
-
observe(this, nameObserver)
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); }
当生命周期处于'DESTROYED'时,直接返回。否则为每一个observer创建LifecycleBoundObserver对象用来感知生命周期。然后保存在mObservers集合中。
-
LifecycleBoundObserver
class LifecycleBoundObserver extends ObserverWrapper implements LifecycleEventObserver { ... @Override boolean shouldBeActive() { // 如果生命周期是STARTED,RESUMED返回true,否则返回false return mOwner.getLifecycle().getCurrentState().isAtLeast(STARTED); } @Override public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) { // 如果生命周期状态是'DESTROYED'者移除observer if (mOwner.getLifecycle().getCurrentState() == DESTROYED) { removeObserver(mObserver); return; } activeStateChanged(shouldBeActive()); } ... }
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) { // 如果状态没有发生改变者不处理,即STARTED,RESUMED与其它状态的转换。 if (newActive == mActive) { return; } mActive = newActive; boolean wasInactive = LiveData.this.mActiveCount == 0; LiveData.this.mActiveCount += mActive ? 1 : -1; // Called when the number of active observers change to 1 from 0,可以认为处于前台的时候 if (wasInactive && mActive) { onActive(); } // Called when the number of active observers change from 1 to 0.可以认为处于后台的时候 if (LiveData.this.mActiveCount == 0 && !mActive) { onInactive(); } if (mActive) { // 如果处于前台,通知数据观察者 dispatchingValue(this); } } }
-
设置数据
mode.currentName.postValue("丘比特")
protected void postValue(T value) { boolean postTask; synchronized (mDataLock) { postTask = mPendingData == NOT_SET; mPendingData = value; } if (!postTask) { return; } ArchTaskExecutor.getInstance().postToMainThread(mPostValueRunnable); }
这里做了异步处理,并且在子线程也会发送到主线程处理。然后就是调用dispatchingValue方法通知数据观察者,这里可以自己点进去看看。
-
可用于计算的ComputableLiveData
通过查看源码,改类实现了对LiveData的扩展,可以在多个子线程完成对某一任务的计算,当所以都计算完成后,通知主线程更新UI。而计算过程由用户实现。
Transformations
val cn: LiveData<String> = Transformations.switchMap(mode.currentBirth){
address -> getPostCode(address)
}
对输入数据进行转换成想要的输出数据,输入数据类型可以和输出不同
MediatorLiveData
对LiveData对象添加数据观察,具体用法请自行查看源码。
总结
LiveData就是可观察的数据持有者类,借助Lifecycles知识进行生命周期感知,但是它没有使用Lifecycles库相关的类,所以是独立的。
网友评论