Skip to content

Instantly share code, notes, and snippets.

@shorti1996
Created January 22, 2020 15:42
Show Gist options
  • Save shorti1996/4f7297df891dc10754dfa8550e4d2b3d to your computer and use it in GitHub Desktop.
Save shorti1996/4f7297df891dc10754dfa8550e4d2b3d to your computer and use it in GitHub Desktop.
LiveData Extensions
import androidx.lifecycle.*
fun <T> MutableLiveData<T>.setValueIfDiffers(newValue: T?, onSet: ((newValue: T?) -> Unit)? = null, onNotSet: (() -> Unit)? = null) {
if (value != newValue) {
value = newValue
onSet?.invoke(newValue)
} else {
onNotSet?.invoke()
}
}
fun <T> MediatorLiveData<T>.addManySources(vararg sources: LiveData<*>, calculate: () -> T?, setValueOnlyIfDiffers: Boolean = false) {
sources.forEach {
addSource(it) {
val newValue = calculate()
if (setValueOnlyIfDiffers) {
setValueIfDiffers(newValue)
} else {
value = newValue
}
}
}
}
fun <T> MutableLiveData<T>.update(block: T.() -> Unit) {
value = value?.also {
block(it)
}
}
fun <T> LiveData<T>?.hasNoActiveObservers() = this?.hasActiveObservers() != true
object LiveDataExtensions {
fun <T> createMediatorLiveDataForSources(
vararg sources: LiveData<*>, calculate: () -> T?,
setValueOnlyIfDiffers: Boolean = false
) = MediatorLiveData<T>().apply {
addManySources(sources = *sources, calculate = calculate, setValueOnlyIfDiffers = setValueOnlyIfDiffers)
}
}
fun <T> LiveData<T>.observe(owner: LifecycleOwner, observer: (T) -> Unit) = observe(owner, Observer(observer))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment