android - ViewModel 的 LiveData 是否可以包含供其各自 View 调用的函数?

标签 android kotlin viewmodel android-livedata android-viewmodel

类似于iamjonfry的方法here ...

简单示例: 除了 ui 内容(即 title )之外,我的数据类( MyUIState )还有 onClicked特性。当MyFragment比如说,一个RecyclerView按钮提交 myViewsDataListAdapter ,适配器设置OnClickListener每个项目的调用相应的 onClicked数据类中的函数(最初来自 ViewModel )

// MyViewModel.kt - Note: It does not reference anything in Activity/Fragment/View layer

// Data Class representing State that will map to the View Layer
data class MyState(val myItems: List<Item>) {

    /* Other properties go here. Not necessary for sake of example */

    // Item will map to a button in the View Layer
    data class Item(
        val title: String,
        val onClicked: (() -> Unit)? // I want to know if this is okay to do
    )
}

//LiveData for Activity/Fragment/View to observe
val myStateLiveData: MutableLiveData<MyState> = MutableLiveData()

fun refreshState() {
    myStateLiveData.value = MyState(
        getRawData().map {
            MyState.Item(
                title = it.title,
                // Note the lambda being passed here...
                onClicked = { /* do stuff in here */ }
            )
        }
    )
}

主要问题: ViewModel 的 LiveData 包含供其各自 View 调用的函数类型(例如,将 onClick 处理程序传递给 View )是否是一种合理的方法?如果不是,正确的标准是什么?

最佳答案

是的,这会泄漏您的 UI 组件。 LiveData 的观察者超出范围时会自动断开连接,因此不会泄露。但是,如果 LiveData 本身存储对捕获 Activity 或 Fragment 中任何内容的 lambda 的间接引用,则该 Activity 或 Fragment 将被泄漏。没有机制可以自动删除代码中的引用。理论上您可以使用 Wea​​kReferences,但这会导致代码变得复杂,并且通过将 UI 引用传递给 ViewModel 无论如何都会违反 MVVM。

关于android - ViewModel 的 LiveData 是否可以包含供其各自 View 调用的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61736742/

相关文章:

java - 从 Bundle getParcelable 有时会导致 java android 中的 BadParcelableException

gradle - 当我在gradle中添加新的源集时“Kotlin not configured”。 (IntelliJ)

kotlin - 在 build.gradle.kts 中设置环境变量

kotlin - Kotlin 是否允许对测试类使用反引号名称?

asp.net-mvc - 使用 View 模型时更新数据库

android - 使用 ViewModel 构造函数而不是 ViewModelProvider 能够根据参数从 Room 数据库中获取数据

android - 自动重新连接 socket 从 wifi 到 4G

android - 处理多值方法返回的最有效方法是什么?

android - 如何添加广播组

asp.net-mvc - 维护ASP.NET MVC中复选框动态列表的状态