Created
December 7, 2018 06:59
-
-
Save afollestad/d1fa7c4d9a88d0056a0b6e2da84dfd95 to your computer and use it in GitHub Desktop.
Similar to an Rx operator. Filters out same-values from LiveData streams.
This file contains 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
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) |
This file contains 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
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