Skip to content

Instantly share code, notes, and snippets.

@Dzendo
Created June 19, 2021 18:22
Show Gist options
  • Save Dzendo/52e326bc01a8cfaf5e410f239cd801db to your computer and use it in GitHub Desktop.
Save Dzendo/52e326bc01a8cfaf5e410f239cd801db to your computer and use it in GitHub Desktop.
modify with inline and crossline
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