You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
valaddOneObserver = object : Observer<Int> {
overridefunonChanged(t: Int?) {
Log.d(TAG, "-- $t ")
}
}
publicinterfaceObserver<T> {
/** * Called when the data is changed. * @param t The new data */voidonChanged(Tt);
}
privatevoidconsiderNotify(ObserverWrapperobserver) {
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.// 检查 UI 的状态,必须满足状态大于 STARTED。if (!observer.shouldBeActive()) {
observer.activeStateChanged(false);
return;
}
// value 更改的次数if (observer.mLastVersion >= mVersion) {
return;
}
observer.mLastVersion = mVersion;
//noinspection unchecked// 回调通知新的 value。observer.mObserver.onChanged((T) mData);
}
AAC: LiveData
[TOC]
对比 mvp 而言,使用大量的接口在 逻辑层和UI 层之间通信,AAC 则使用 livedata 进行通信。
基本使用
下面简单的演示如何在两者进行通信:
输出结果如下:
可以看到无论调用 addOne() 几次,都在回调之前执行,只输入一次结果,带着问题往下看源码。
源码分析
下面看一下 bindData 的内容。
下面看一下 ViewModel 的结果如何通知到 UI 层面。
这里的方法需要说明一下,由于 postValue 可以执行在线程池,所以结果时抛到主线程去执行;因此对于一下结果:
b 首先会被设置,然后再设置a。
另外,如果在主线程执行完毕之前 post 多次结果,只有最后的一次结果会回调分发。
总结
LiveData 相当于 UI 和 ViewModel 之前的桥梁,当 UI 产生执行动作,而 ViewModel 执行逻辑,从数据库或者网络拿到数据后, 从不同线程使用 livedata postvalue 到 UI 进行操作。
是为 MVVM 架构, 也是数据驱动, 响应式编程的表现。
The text was updated successfully, but these errors were encountered: