Android LiveData:未收到所有通知

Android LiveData: Not receiving all notifications

我正在试验 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实际上运行s并将mPendingData重置为NOT_SET,除了最后一个更新值外,所有更新值都丢失了。在这种情况下,只有一个更新来自 Observer 最新值。