美文网首页
Android livedata多次触发

Android livedata多次触发

作者: FFF_Wang | 来源:发表于2022-01-13 20:26 被阅读0次

    event多次触发
    https://medium.com/androiddevelopers/livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case-ac2622673150

    
    import androidx.lifecycle.Observer
    
    /**
     * 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
    
        /**
         * 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 { value ->
                onEventUnhandledContent(value)
            }
        }
    }```
    

    相关文章

      网友评论

          本文标题:Android livedata多次触发

          本文链接:https://www.haomeiwen.com/subject/fshocrtx.html