Android LiveData:未收到所有通知 [英] Android LiveData: Not receiving all notifications

查看:852
本文介绍了Android LiveData:未收到所有通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Android的 LiveData .我只是试图向观察LiveData对象的观察者推送很多通知.我让线程在后台运行,并在while循环中通过LiveData的postValue方法不断推送随机值.在观察者中观察实时数据的通知的数量(onChanged()回调的数量)比后台线程中postValue的调用数量少得多.

I'm experimenting with Android's LiveData. I just tried to push a lot of notifications to an observer that observes a LiveData object. I let a thread run in background and in a while-loop i constantly push random values via LiveData's postValue-method. The number of received notifications (number of onChanged()-callbacks) in the observer which observes the livedata is much less then the number of calls of postValue in the background thread.

有人可以解释这是什么原因吗?

Can somebody explain what's the reason for this?

提前谢谢

推荐答案

解释在于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仅更新一次具有最新值.
  1. On the first run, in postValue mPendingData = NOT_SET so the following if (!postTask) condition is false and thus mPostValueRunnable is sent to the main thread.
  2. On the second run, if the mPostValueRunnable hasn't been executed yet (it may not as values are updated extremely frequently), the if is true and so nothing is sent to the main thread except that mPendingData is set to a new value.
  3. On the third run, it can be the same as on the previous one and so on for some number of updates. Thereof, until mPostValueRunnable actually runs and resets mPendingData to NOT_SET, all the update values are lost except for the last one. In this case, only one update comes via Observer with the latest value.

这篇关于Android LiveData:未收到所有通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆