简体   繁体   English

如何使用房间数据库作为缓存

[英]How to use room database as a cache

I am making an android app using MVVM architecture.我正在使用 MVVM 架构制作一个 android 应用程序。 I want to fetch data from an API and insert it into room database and then fetch it from the room in my app.我想从 API 中获取数据并将其插入房间数据库,然后在我的应用程序中从房间中获取它。 I don't know if it is a better way to implement database cache functionality.不知道是不是更好的实现数据库缓存功能的方式。 If there is some other or better way to do so please let me know.如果有其他或更好的方法,请告诉我。

your question explains exactly how you would use Room: 您的问题确切说明了如何使用Room:

  1. fetch data from an api 从api获取数据
  2. insert it into room database 将其插入房间数据库
  3. fetch it from room in my app 从我的应用程序的房间中获取

Room allows you to store your data locally and retrieve this data with various different threads, making use of something like Rxjava, it also allows you to observe onto any changes with LiveData, Room is definitely a decent option to consider for caching Room允许您使用Rxjava之类的东西在本地存储数据并使用各种不同的线程检索此数据,它还允许您观察LiveData的任何变化,Room绝对是考虑进行缓存的不错的选择

BUT

Using Room is ONE of SEVERAL different implementations of caching, consider posting code or a specific scenario for better answers. 使用Room是缓存的几种不同实现之一,请考虑发布代码或特定方案以获得更好的答案。 Happy coding. 快乐的编码。

Edit: 编辑:

A common approach to using Room (or any caching) would be to either load initial data from the database, display this to the user, perform an api call, update the cache and display this updated data from the api 使用Room(或任何缓存)的一种常见方法是从数据库加载初始数据,将其显示给用户,执行api调用,更新缓存并从api显示此更新的数据

OR 要么

If the user does not have an internet connection, simply use what he has available in the cache as data. 如果用户没有Internet连接,则只需使用其缓存中可用的数据作为数据。 Again, all of this depends on your specific scenario. 同样,所有这些都取决于您的特定方案。

Use database for the cache is not cheap, better use shared preferences for caching your data. 使用数据库进行缓存并不便宜,最好使用共享首选项来缓存数据。

You can implement a class for cache data or use a library full feature for cache like kesho 您可以实现用于缓存数据的类,也可以使用库的完整功能来缓存诸如kesho

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM