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

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

问题描述

我有一个单独的类,负责处理数据提取(特别是Firebase),通常从中返回LiveData对象并异步更新它们.现在,我想将返回的数据存储在ViewModel中,但是问题是,为了获取所述值,我需要观察从数据获取类返回的LiveData对象.观察方法要求将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?

推荐答案

此博客文章,在这种情况下,建议使用转换(请参见存储库中的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天全站免登陆