Using LiveData in SnackBar, Navigation and other events - Moment For Technology

PHOTO EMBED

Thu May 19 2022 09:30:49 GMT+0000 (UTC)

Saved by @toufiqakbar #kotlin

/**
 * 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) {

    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 }Copy the code
content_copyCOPY

https://www.mo4tech.com/using-livedata-in-snackbar-navigation-and-other-events.html