Created
December 7, 2021 19:05
-
-
Save Kashif-E/859562319ef469a682777d1b10d2221f to your computer and use it in GitHub Desktop.
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
/** | |
* Used as a wrapper for data that is exposed via a LiveData that represents an event. | |
*/ | |
open class Event<out T>(private val content: T) { | |
@Suppress("MemberVisibilityCanBePrivate") | |
var hasBeenHandled = false | |
private set // Allow external read but not write | |
/** | |
* Returns the content and prevents its use again. | |
*/ | |
fun getContentIfNotHandled(): T? { | |
return if (hasBeenHandled) { | |
null | |
} else { | |
hasBeenHandled = true | |
content | |
} | |
} | |
/** | |
* Returns the content, even if it's already been handled. | |
*/ | |
fun peekContent(): T = content | |
} | |
/** | |
* An [Observer] for [Event]s, simplifying the pattern of checking if the [Event]'s content has | |
* already been handled. | |
* | |
* [onEventUnhandledContent] is *only* called if the [Event]'s contents has not been handled. | |
*/ | |
class EventObserver<T>(private val onEventUnhandledContent: (T) -> Unit) : Observer<Event<T>> { | |
override fun onChanged(event: Event<T>?) { | |
event?.getContentIfNotHandled()?.let { | |
onEventUnhandledContent(it) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment