Skip to content

Instantly share code, notes, and snippets.

@nadar71
Created October 21, 2020 09:48
Show Gist options
  • Save nadar71/1e147b6d76579ec35f7a7edd96b36d5a to your computer and use it in GitHub Desktop.
Save nadar71/1e147b6d76579ec35f7a7edd96b36d5a to your computer and use it in GitHub Desktop.
Extension to avoid false positive in room query
/*
Extension to avoid false positive in room query :
https://stackoverflow.com/questions/47215666/room-livedata-from-dao-will-trigger-observer-onchanged-on-every-update-even-i
https://medium.com/androiddevelopers/7-pro-tips-for-room-fbadea4bfbd1#5e38
*/
fun <T> LiveData<T>.getDistinct(): LiveData<T> {
val distinctLiveData = MediatorLiveData<T>()
distinctLiveData.addSource(this, object : Observer<T> {
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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment