Room : LiveData from Dao will trigger Observer.onChanged on every Update, even if the LiveData value has no change

前端 未结 5 1368
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-05 10:14

I found that the LiveData returned by Dao will call its observer whenever the row is updated in DB, even if the LiveData value is obviously not changed.

Consider a s

5条回答
  •  一个人的身影
    2020-12-05 10:49

    This situation is known as false positive notification of observer. Please check point number 7 mentioned in the link to avoid such issue.

    Below example is written in kotlin but you can use its java version to get it work.

    fun  LiveData.getDistinct(): LiveData {
        val distinctLiveData = MediatorLiveData()
        distinctLiveData.addSource(this, object : Observer {
            private var initialized = false
            private var lastObj: T? = null
            override fun onChanged(obj: T?) {
                if (!initialized) {
                    initialized = true
                    lastObj = obj
                    distinctLiveData.postValue(lastObj)
                } else if ((obj == null && lastObj != null) 
                           || obj != lastObj) {
                    lastObj = obj
                    distinctLiveData.postValue(lastObj)
                }
            }
        })
        return distinctLiveData
    }
    

提交回复
热议问题