Using a closure: ``` fun <T> LiveData<T&g...
# announcements
a
Using a closure:
Copy code
fun <T> LiveData<T>.distinct(): LiveData<T> {
    var lastValue: Any? = Any()

    return MediatorLiveData<T>().apply {
        addSource(this@distinct) {
            if (it != lastValue) {
                lastValue = it
                postValue(it)
            }
        }
    }
}
Or using a property of the object:
Copy code
fun <T> LiveData<T>.distinct(): LiveData<T> {
    return MediatorLiveData<T>().apply {
        addSource(this@distinct, object : Observer<T> {

            private var lastValue: Any? = Any()

            override fun onChanged(value: T?) {
                if (value != lastValue) {
                    lastValue = value
                    postValue(value)
                }
            }

        })
    }
}
Any arguments to prefer one over the other?
1️⃣ 1
c
second is less readable
k
the closure is definitely more readable