如何从服务中的Room数据库读取数据和侦听更改? [英] How to read data and listen to changes from Room database in a Service?
问题描述
现在,我想分析所有过去的用户数据,以便为将来的决策提供建议.我的建议会随着用户对数据库的每次更改而改变,因此我需要经常更新自己的建议,同时一遍又一遍地进行相同的计算.
我当时正在考虑在应用启动时启动一项服务,该服务通过ViewModel和LiveData侦听数据库更改并更新我的建议(这些建议也存储在同一数据库中).但是某种方式服务不能
- 通过
viewModel = ViewModelProviders.of(this).get(DataViewModel.class);
获取ViewModel
- 观察LiveData对象,因为它不是LifecycleOwner.
基本上,每次数据库内容更改时,我只需要读取数据库中的所有条目,分析数据并更新5-10个值即可.
如果不在服务中,我应该如何以及在哪里进行计算?也许我陷入了一个错误的想法,而服务却不是正确的方法,因此非常感谢您提供有关如何执行此操作的任何想法!
观察LiveData对象,因为它不是LifecycleOwner
在LiveData
上使用observeForever()
,并在适当的时候通过removeObserver()
手动注销(该服务的onDestroy()
,如果不早的话).
请记住,此处适用标准服务限制(例如,除非服务是前台服务,否则它们在Android 8.0+上运行约1分钟),因此您可能仍然需要考虑其他方法.
i am storing user information in a local room database. In activities and fragments I use AndroidViewModel and LiveData to listen to changes made to the database and update the UI.
Now I want to analyze all of the past user data to give recommendations for future decisions. My recommendations change on every change to the database made by the user so I need to update my reommendations frequently while doing the same calculations over and over again.
I was thinking about starting a service on app start that listens to database changes via ViewModel and LiveData and updates my recommendations (which are also stored in the same database). But somehow a Service cannot
- get a ViewModel via
viewModel = ViewModelProviders.of(this).get(DataViewModel.class);
- observe a LiveData object as it is not a LifecycleOwner.
Basically I simply need to read all entries from the database, analyze the data and update 5-10 values every time the database content changes.
How and where should I do my calculations if not in a service? Maybe I am trapped in a wrong thought and a service is not the right way to do it so any idea on how to do this is very much appreciated!
observe a LiveData object as it is not a LifecycleOwner
Use observeForever()
on the LiveData
, manually unregistering via removeObserver()
when appropriate (onDestroy()
of the service, if not sooner).
Bear in mind that standard service limitations apply here (e.g., services run for ~1 minute on Android 8.0+ unless they are foreground services), so it may be that you need to consider other approaches anyway.
这篇关于如何从服务中的Room数据库读取数据和侦听更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!