gpt4 book ai didi

安卓实时数据 : Not receiving all notifications

转载 作者:太空狗 更新时间:2023-10-29 13:48:05 27 4
gpt4 key购买 nike

我正在试验 Android 的 LiveData .我只是试图将大量通知推送给观察 LiveData 对象的观察者。我让一个线程在后台运行,在一个 while 循环中,我不断地通过 LiveData 的 postValue 方法推送随机值。观察 livedata 的观察者中收到的通知数(onChanged()-回调数)远少于后台线程中 postValue 的调用数。

谁能解释一下这是什么原因?

提前致谢

最佳答案

解释在于 postValuemPostValueRunnable 的实现:

protected void postValue(T value) {
boolean postTask;
synchronized (mDataLock) {
//this is true on the first run or right after the observer receives an update
postTask = mPendingData == NOT_SET;
mPendingData = value;
}
// this statement will be true if the observer hasn't received an update even though it's sent to the main looper
if (!postTask) {
return;
}
ArchTaskExecutor.getInstance().postToMainThread(mPostValueRunnable);
}

private final Runnable mPostValueRunnable = new Runnable() {
@Override
public void run() {
Object newValue;
synchronized (mDataLock) {
newValue = mPendingData;
mPendingData = NOT_SET;//once this value is reset a new mPostValueRunnable can be sent
}
// here the observer will receive the update
setValue((T) newValue);
}
};
  1. 在第一次运行时,在 postValue mPendingData = NOT_SET 中,因此以下 if (!postTask) 条件为 false,因此 mPostValueRunnable 被发送到主线程。
  2. 在第二次运行时,如果 mPostValueRunnable 还没有被执行(它可能不会因为值更新非常频繁),iftrue 因此除了将 mPendingData 设置为新值外,没有任何内容发送到主线程。
  3. 在第三次运行时,它可以与上一次相同,依此类推进行一些更新。因此,直到mPostValueRunnable实际运行并将mPendingData重置为NOT_SET,除最后一个值外,所有更新值都将丢失。在这种情况下,只有一个更新来自 Observer 并具有最新值。

关于安卓实时数据 : Not receiving all notifications,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51031062/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com