如何将API的响应存储在缓存中,并在每12小时后调用API?

huangapple go评论46阅读模式
英文:

How to store response of an api in cache and call api after every 12 hours?

问题

我有一个API调用,它在JSON响应中包含图像和文本的列表,我想将JSON存储在本地并在UI中使用它。API应该在每12小时后调用,并将数据保存在缓存或内部存储中。API调用在列表屏幕上,可以在按钮点击时打开。

哪种方法更合适?如何在特定屏幕中调用API,即使应用程序已关闭?
哪种方法更适合存储响应,缓存还是使用sharedprefrence?
我已经使用了dio和retrofit作为API调用的辅助工具。

我尝试过使用Cron并将数据保存在sharedpref中。
我尝试过使用Flutter缓存管理器,但效果不佳。
我尝试过使用dio缓存管理器,但与dio的子模块retrofit不兼容。

请为此提供解决方案。

英文:

I have an api call that have list of images and text in json response, i want to store json in local and use it in the ui, The api should be called after every 12 hours and save data in cache or the internal storage.
Api call is in the listscreen that opens on a button click.

which one is more suitable. How can i call an api in certain screen even when the app is closed?
Which one is more prefereble to store response cache or using sharedprefrence?
I have used dio and retrofit as sub for the api call.

I tried using Cron and save data in sharedpref.
i tried using flutter cache manager but didnt fit well.
i tried using dio cache mnanager but it didnt work well with retrofit submodule with dio.

Please suggest solution for this.

答案1

得分: 0

我使用共享首选项和计时器对象完成了这个任务。我将响应存储在首选项中,并在后台设置了一个计时器,根据要求,API应在每12小时后调用。

主要逻辑是在应用程序启动时启动计时器,并在用户关闭应用程序时存储时间戳。因此,当用户再次启动应用程序时,我会检查用户上次关闭应用程序的时间,并计算时间,如果时间小于12小时,我会继续计时器,否则我会调用API。

这就是我如何设法在本地保存API响应的方法,如果首选项中找不到数据,我会立即调用API。

英文:

I have done by using shared preference and timer object, As i stored my response in preference and put a timer in the background, As per requirement the api should be called after each 12 hours finished.

> So main logic was i start the timer when the app is launched and i
> store the time stamp when user closes the app, so when user again
> start the app i check with the last time user has closed the app and
> counts the time if its less then 12 hours I will continue timer or I
> will call the API.

So this is how I managed to save API response in local and if the data is not found in the preference I would call the API right away.

huangapple
  • 本文由 发表于 2023年2月14日 20:47:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/75448064.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定