Skip to content

Instantly share code, notes, and snippets.

@rezaiyan
Created January 17, 2021 14:15
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 rezaiyan/e8443918ddf8ac5b60e2555e23460e93 to your computer and use it in GitHub Desktop.
Save rezaiyan/e8443918ddf8ac5b60e2555e23460e93 to your computer and use it in GitHub Desktop.
liveData.observeLimit({
//asset 1
}, {
//assert 2
})...
import androidx.lifecycle.*
/**
* Observer implementation that owns its lifecycle and achieves a one-time only observation
* by marking it as destroyed once the onChange handler is executed.
*
* @param handler the handler to execute on change.
*/
class OneTimeObserver<T>(private val onChangeHandler: Array<out (T) -> Unit>) :
Observer<T>, LifecycleOwner {
private val lifecycle = LifecycleRegistry(this)
var calls = 0
init {
lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_RESUME)
}
override fun getLifecycle(): Lifecycle = lifecycle
override fun onChanged(t: T) {
if (calls < onChangeHandler.size) {
onChangeHandler[calls].invoke(t)
calls++
}
if (calls == onChangeHandler.size) {
calls = 0
lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY)
}
}
}
fun <T> LiveData<T>.observeLimit(vararg onChangeHandler: (T) -> Unit) {
val observer = OneTimeObserver(onChangeHandler)
observe(observer, observer)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment