Skip to content

Instantly share code, notes, and snippets.

@DanielKnauf
Last active April 17, 2021 14:32
Show Gist options
  • Save DanielKnauf/84d49012e467d669729bcd51e20e5e1e to your computer and use it in GitHub Desktop.
Save DanielKnauf/84d49012e467d669729bcd51e20e5e1e to your computer and use it in GitHub Desktop.
Excerpt of MergerLiveData from LiveData-Kit for Medium article
sealed class MergerLiveData<TargetType> : MediatorLiveData<TargetType>() {
// One
class Two<FirstSourceType, SecondSourceType, TargetType>(
private val firstSource: LiveData<FirstSourceType>,
private val secondSource: LiveData<SecondSourceType>,
private val distinctUntilChanged: Boolean = true,
private val merging: (FirstSourceType, SecondSourceType) -> TargetType
) : MediatorLiveData<TargetType>() {
override fun onActive() {
super.onActive()
addSource(firstSource) { value ->
val newValue =
merging(
value,
secondSource.value ?: return@addSource
)
postValue(
distinctUntilChanged = distinctUntilChanged,
newValue = newValue
)
}
addSource(secondSource) { value ->
val newValue =
merging(
firstSource.value ?: return@addSource,
value
)
postValue(
distinctUntilChanged = distinctUntilChanged,
newValue = newValue
)
}
}
override fun onInactive() {
removeSource(firstSource)
removeSource(secondSource)
super.onInactive()
}
}
// Three, ...
}
private fun <T> MediatorLiveData<T>.postValue(
distinctUntilChanged: Boolean,
newValue: T
) {
val value = value ?: postValue(newValue)
if (distinctUntilChanged && value == newValue) return
postValue(newValue)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment