类似于iamjonfry的方法here ...
简单示例:
除了 ui 内容(即 title
)之外,我的数据类( MyUIState
)还有 onClicked
特性。当MyFragment
比如说,一个RecyclerView
按钮提交 myViewsData
到 ListAdapter
,适配器设置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 将被泄漏。没有机制可以自动删除代码中的引用。理论上您可以使用 WeakReferences,但这会导致代码变得复杂,并且通过将 UI 引用传递给 ViewModel 无论如何都会违反 MVVM。
关于android - ViewModel 的 LiveData 是否可以包含供其各自 View 调用的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61736742/