https://kotlinlang.org logo
Title
a

arekolek

01/14/2018, 12:07 PM
Using a closure:
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:
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

Czar

01/14/2018, 1:20 PM
second is less readable
k

kevinmost

01/14/2018, 4:33 PM
the closure is definitely more readable