Created
January 17, 2021 14:15
-
-
Save rezaiyan/e8443918ddf8ac5b60e2555e23460e93 to your computer and use it in GitHub Desktop.
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
liveData.observeLimit({ | |
//asset 1 | |
}, { | |
//assert 2 | |
})... |
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
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