Created
October 21, 2020 09:48
-
-
Save nadar71/1e147b6d76579ec35f7a7edd96b36d5a to your computer and use it in GitHub Desktop.
Extension to avoid false positive in room query
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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