Skip to content

Instantly share code, notes, and snippets.

@twyatt
Created January 10, 2019 06:30
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 twyatt/dea4c2fdb6d9c04fb474f8e13d5d8e33 to your computer and use it in GitHub Desktop.
Save twyatt/dea4c2fdb6d9c04fb474f8e13d5d8e33 to your computer and use it in GitHub Desktop.
LiveData extension function that prevents emissions from receiver until after trigger emits a value that satisfies predicate.
/**
* Prevent emissions from receiver until after [trigger] emits a value that satisfies [predicate].
*/
private fun <T, R> LiveData<T>.allowAfter(
trigger: LiveData<R>,
predicate: (R?) -> Boolean
) = object : MediatorLiveData<T?>() {
private var isReady = false
private var hasValue = false
private var pendingValue: T? = null
init {
addSource(this@allowAfter) {
hasValue = true
pendingValue = it
emit()
}
addSource(trigger) {
if (predicate.invoke(it)) {
isReady = true
}
emit()
}
}
private fun emit() {
if (isReady && hasValue) {
value = pendingValue
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment