Android:从服务在 ViewModel 中设置 LiveData
我设置应用程序的方式是,服务将在后台获取一些信息,这些信息需要由片段实时获取,然后显示它进入一个视图。为此,我将数据放入 ViewModel 中,并让我的 Fragment 观察 ViewModel 中的 LiveData。
问题是,我在 设置/更改 ViewModel 类中的 LiveData 时遇到问题 看来 ViewModel 是要在 Activity 和 Fragments 之间使用的,而且我似乎无法在我的服务中获取 ViewModel 来更改我的 Fragment 需要观察的值。有办法实现吗?
The way I have my app set up is that, the Service will be getting some information in the background, which needs to be acquired live by the Fragment, and then display it into a view. To do this, I put the data inside a ViewModel and let my Fragment observe the LiveData in the ViewModel.
The problem is, I am having trouble setting/changing the LiveData inside the ViewModel class from the service. It seems that ViewModel is meant to be used between Activities and Fragments, and I cannot seem to get the ViewModel inside my service in order to change the value that needs to be observed by my Fragment. Is there a way to implement this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能希望使用具有自己的 MutableLiveData 字段的存储库,该字段在您的服务中进行修改。然后,您的 ViewModel 将有一个指向 Repository 字段的 MutableLiveData 字段,并且您的 Fragment 可以观察该字段。
片段:
ViewModel:
存储库:
服务:
You probably want to use a Repository with its own MutableLiveData field that is modified within your service. Your ViewModel will then have a MutableLiveData field that points to the Repository field, and your Fragment can observe that field.
Fragment:
ViewModel:
Repository:
Service: