如何停止LiveData事件被多次触发 [英] How to stop LiveData event being triggered more than Once

查看:1551
本文介绍了如何停止LiveData事件被多次触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在应用程序中使用MutableLiveData进行基于事件的通信.我有单一活动两个片段的体系结构.

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

借助ViewModel,我正在使用Fragment-1中的LiveData事件.但是,当我使用菜单栏将Fragment-1替换为Fragment-2并最终返回Fragment-1时,LiveData的旧值又被捕获了.

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.

推荐答案

您可以使用Event来包装LiveData值,以使用其值,如以下文章所述: https://medium. com/androiddevelopers/livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case-ac2622673150

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

事件类如下:

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
}

让我们说您的LiveData值是一个字符串,那么单个事件的LiveData就像:

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

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

这篇关于如何停止LiveData事件被多次触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆