Created
January 10, 2019 06:30
-
-
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.
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
/** | |
* 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