Last active
April 17, 2021 14:32
-
-
Save DanielKnauf/84d49012e467d669729bcd51e20e5e1e to your computer and use it in GitHub Desktop.
Excerpt of MergerLiveData from LiveData-Kit for Medium article
This file contains hidden or 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
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