A class that encapsulates data, adding ability to know when the data has already been viewed. Useful for putting one-shot events, like "display dialog", into a State object that can be reapplied to a view.
| import java.util.concurrent.atomic.AtomicBoolean | |
| /** | |
| * Wraps some data that should track when it has been viewed and allow future viewers to avoid a second showing. | |
| * Useful for showing messages in the app that auto-hide because this class can exist in the app's state. | |
| */ | |
| data class ViewOnceData<T>(private val data: T) { | |
| val wasViewed = AtomicBoolean(false) | |
| /** | |
| * Returns the data if it has not been viewed before and marks it as viewed. | |
| * If it has been previously viewed, returns null. | |
| */ | |
| fun getDataIfNotViewed(): T? { | |
| return if (wasViewed.compareAndSet(false, true)) { | |
| data | |
| } else { | |
| null | |
| } | |
| } | |
| /** | |
| * Returns the data regardless of viewed status. | |
| */ | |
| fun peek() = data | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment