【问题标题】:Android LiveData: Not receiving all notificationsAndroid LiveData:未收到所有通知
【发布时间】:2018-12-04 11:27:04
【问题描述】:

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

谁能解释这是什么原因?

提前谢谢你

【问题讨论】:

  • 我在帖子之间尝试了不同的睡眠间隔。当我试图检查我的应用程序对大量数据的反应时,我让 thead 在两者之间休眠一纳秒
  • 您找到解决问题的方法了吗?我有类似的问题。
  • 没有。我尝试执行压力测试,在其中我最大化推送通知的数量。原来 LiveData 类的机制增加了我程序的健壮性,所以我没有尝试改变 LiveData 类的行为。

标签: android frequency observer-pattern android-livedata


【解决方案1】:

解释在于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 的更新具有最新值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-06
    • 2013-07-28
    • 2021-07-03
    相关资源
    最近更新 更多