Created
June 14, 2020 14:47
-
-
Save GregKluska/6f332a3086812f008cc7039090623bba to your computer and use it in GitHub Desktop.
Used as a wrapper for data that is exposed via a LiveData that represents an event.
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
| /** | |
| * Used as a wrapper for data that is exposed via a LiveData that represents an event. | |
| */ | |
| class Event<T>(private val content: T) { | |
| 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 | |
| override fun toString(): String { | |
| return "Event(content=$content,hasBeenHandled=$hasBeenHandled)" | |
| } | |
| companion object{ | |
| // we don't want an event if there's no data | |
| fun <T> dataEvent(data: T?): Event<T>?{ | |
| data?.let { | |
| return Event(it) | |
| } | |
| return null | |
| } | |
| // we don't want an event if there is no message | |
| fun messageEvent(message: String?): Event<String>?{ | |
| message?.let{ | |
| return Event(message) | |
| } | |
| return null | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment