Skip to content

Instantly share code, notes, and snippets.

@afollestad
Created December 7, 2018 06:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afollestad/d1fa7c4d9a88d0056a0b6e2da84dfd95 to your computer and use it in GitHub Desktop.
Save afollestad/d1fa7c4d9a88d0056a0b6e2da84dfd95 to your computer and use it in GitHub Desktop.
Similar to an Rx operator. Filters out same-values from LiveData streams.
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.Observer
/** @author Aidan Follestad (@afollestad) */
class DistinctLiveData<T>(source1: LiveData<T>) : MediatorLiveData<T>() {
private var isInitialized = false
private var lastValue: T? = null
init {
super.addSource(source1) {
if (!isInitialized) {
value = it
isInitialized = true
lastValue = it
} else if (lastValue != it) {
value = it
lastValue = it
}
}
}
override fun <S : Any?> addSource(
source: LiveData<S>,
onChanged: Observer<in S>
) {
throw UnsupportedOperationException()
}
override fun <T : Any?> removeSource(toRemote: LiveData<T>) {
throw UnsupportedOperationException()
}
}
fun <T> LiveData<T>.distinct(): MediatorLiveData<T> = DistinctLiveData(this)
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.lifecycle.MutableLiveData
import org.junit.Rule
import org.junit.Test
/** @author Aidan Follestad (@afollestad) */
class DistinctTest {
@Rule @JvmField val rule = InstantTaskExecutorRule()
@Test fun filterLastValues() {
val data = MutableLiveData<String>()
val distinct = data.distinct()
.test()
data.postValue("Hello")
data.postValue("Hello")
data.postValue("Hi")
data.postValue("Hi")
data.postValue("Hello")
distinct.assertValues(
"Hello",
"Hi",
"Hello"
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment