如何从服务中的Room数据库读取数据和侦听更改? [英] How to read data and listen to changes from Room database in a Service?

查看:427
本文介绍了如何从服务中的Room数据库读取数据和侦听更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将用户信息存储在本地会议室数据库中.在活动和片段中,我使用AndroidViewModel和LiveData侦听对数据库所做的更改并更新UI.

现在,我想分析所有过去的用户数据,以便为将来的决策提供建议.我的建议会随着用户对数据库的每次更改而改变,因此我需要经常更新自己的建议,同时一遍又一遍地进行相同的计算.

我当时正在考虑在应用启动时启动一项服务,该服务通过ViewModel和LiveData侦听数据库更改并更新我的建议(这些建议也存储在同一数据库中).但是某种方式服务不能

  1. 通过viewModel = ViewModelProviders.of(this).get(DataViewModel.class);
  2. 获取ViewModel
  3. 观察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

  1. get a ViewModel via viewModel = ViewModelProviders.of(this).get(DataViewModel.class);
  2. 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屋!

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