从 ViewModel 观察 LiveData [英] Observing LiveData from ViewModel

查看:38
本文介绍了从 ViewModel 观察 LiveData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个单独的类,我在其中处理数据获取(特别是 Firebase),我通常从中返回 LiveData 对象并异步更新它们.现在我想将返回的数据存储在 ViewModel 中,但问题是为了获得所述值,我需要观察从我的数据获取类返回的 LiveData 对象.observe 方法需要 LifecycleOwner 对象作为第一个参数,但我的 ViewModel 中显然没有这个对象,而且我知道我不应该在 ViewModel 中保留对 Activity/Fragment 的引用.我该怎么办?

I have a separate class in which I handle data fetching (specifically Firebase) and I usually return LiveData objects from it and update them asynchronously. Now I want to have the returned data stored in a ViewModel, but the problem is that in order to get said value, I need to observe the LiveData object returned from my data fetching class. The observe method required a LifecycleOwner object as the first parameter, but I obviously don't have that inside of my ViewModel and I know I am not supposed to keep a reference to the Activity/Fragment inside of the ViewModel. What should I do?

推荐答案

这篇博文 由 Google 开发人员 Jose Alcérreca 撰写,建议在这种情况下使用转换(请参阅存储库中的 LiveData"段落),因为 ViewModel 不应包含任何与 View(活动、上下文等)相关的参考,因为它很难测试.

In this blog post by Google developer Jose Alcérreca it is recommended to use a transformation in this case (see the "LiveData in repositories" paragraph) because ViewModel shouldn't hold any reference related to View (Activity, Context etc) because it made it hard to test.

这篇关于从 ViewModel 观察 LiveData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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