Created
June 19, 2021 18:22
-
-
Save Dzendo/52e326bc01a8cfaf5e410f239cd801db to your computer and use it in GitHub Desktop.
modify with inline and crossline
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
open class Event<out T>(private val content: T? = null) { | |
@Suppress("MemberVisibilityCanBePrivate") | |
var hasBeenHandled = false | |
private set | |
// Returns the content and prevents its use again. | |
fun getContentIfNotHandled(): T? = if (hasBeenHandled) null else content.also { hasBeenHandled = true } | |
// Returns the content, even if it's already been handled. | |
fun peekContent(): T? = content | |
} | |
inline fun <T> LiveData<Event<T>>.observeEvent(owner: LifecycleOwner, crossinline onEventUnhandledContent: (T) -> Unit) { | |
observe(owner) { it?.getContentIfNotHandled()?.let(onEventUnhandledContent) } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment