How to stop LiveData event being triggered more than Once

泄露秘密 提交于 2019-12-11 08:11:54

问题


I am using MutableLiveData within my application for event based communication. I have single activity two fragments architecture.

With the help of ViewModel, I'm consuming the LiveData events in Fragment-1. But, when I replace this Fragment-1 with Fragment-2 using Menu bar and finally come back to Fragment-1, old values of LiveData are captured again.

How to avoid this problem? Any help/suggestions are highly appreciated! Thank you.


回答1:


You can use Event to wrap LiveData values to handle consuming its values as in the following article: https://medium.com/androiddevelopers/livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case-ac2622673150

Event class would be like:

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
}

Let us say that your LiveData value is a String then the LiveData of single event would be like:

val navigateToDetails = MutableLiveData<Event<String>>()




回答2:


Wherever you're observing the liveData, in onChanged method remove the observers by calling myLiveDataObject.removeObservers(this); This will remove the observer after first-time data is observed.



来源:https://stackoverflow.com/questions/54688838/how-to-stop-livedata-event-being-triggered-more-than-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!