我正在编写一个(尝试)遵循 MVVM 设计模式的应用程序。我想从该层的其他部分观察模型层的变化。例如
假设我正在使用 room 从我的数据库中公开对象列表:
@Dao
interface MyDao {
@Query("SELECT * FROM myTable")
fun getAllElements(): LiveData<List<Element>>
}
我希望能够像通常使用生命周期所有者那样使用 LiveData.observeForever() 观察变化。
类似:
class BusinessLogicPartOfTheModel(private val myDao: MyDao) {
private var allElements = listOf<Element>()
init {
myDao.getAllElements().observeForever { observedElements ->
allElements = observedElements
}
}
但是,我发现如果我像这样在 ViewModel 和 Fragment 中注册一个像这样的观察者以及一个更标准的观察者:
class MyViewModel(private val myDao: MyDao) : ViewModel() {
fun getAllElements(): LiveData<List<Elements>> {
myDao.getAllElements()
}
}
class MyFragment : Fragment() {
private val myDao /* initialized here */
private val myViewModel /* initialized here */
private val logic = BusinessLogicPartOfTheModel(myDao)
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val obs = Observer<List<Element>> {
// do a thing
}
myViewModel.getAllElements.observe(viewLifeCycleOwner, obs)
}
}
只调用 fragment 中的观察者,不调用业务逻辑对象中的观察者。我可以成功地观察 fragment 中的更新并将事件传递回业务逻辑,但这似乎是一个非常不必要的间接级别。我是不是漏掉了一步,或者这不太可能按照我想要的方式运行?
最佳答案
您可能应该使用 MediatorLiveData相反。
MediatorLiveData
通过将另一个 LiveData
添加到 MediatorLiveData
来接受它作为事件源。
你可以使用类似的东西,
val mediatorLiveData = MediatorLiveData<Item>().apply {
addSource(yourLiveData) {
// do something here
}
}
您还可以查看 Transformations .
Transformations
具有诸如 Transformation.map()
和 Transformation.switchMap()
之类的方法,它们仅使用 MediatorLiveData
引擎盖下。
关于android - 在没有 LifecycleObserver 的情况下使用 LiveData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53491279/