我正在使用 RoboSpice 并希望在我的应用程序中具有以下行为:
- 用户启动一个需要服务器数据的 Activity
- spiceManager 检查数据是否被缓存,如果是则返回它。
- 无论缓存数据是否返回,都会向服务器发起请求
- 当新数据从服务器到达时,我用它更新 UI(如果 Activity 仍然活跃)
它应该类似于 facebook 应用程序:当您打开它时,您会立即看到一个过时的时间线,并最终收到更新。
起初我认为 spiceManager.getFromCacheAndLoadFromNetworkIfExpired()
是实现此目的的好方法,但如果数据已缓存且有效,它只会返回缓存,而不会在其后立即发出网络请求。我用 DurationInMillis.ALWAYS_EXPIRED
和 DurationInMillis.ALWAYS_RETURNED
都试过了。
我是否应该使用 getFromCache()
来检索缓存数据,然后从 onRequestSuccess()
中调用 spiceManager.execute()
always_expired 作为参数?或者有更好/更简单的方法来做到这一点?
在此先感谢您的帮助!
[编辑] 这些链接可能会增加讨论: https://groups.google.com/forum/#!topic/robospice/n5ffupPIpkE/discussion https://groups.google.com/forum/#!topic/robospice/LtoqIXk5JpA
最佳答案
我有相同的任务并使用了来自 here 的方法:
- 如果存在,从缓存中加载 View 数据
- 与此同时,触发从网络加载新版本的请求。如果数据已更改,请更新 View 。
这里是示例代码
SpecialOffersRequest request = new SpecialOffersRequest();
spiceManager.getFromCache(SpecialOffer.List.class, request.getCacheKey(), ALWAYS_RETURNED, new SpecialOffersRequestListener());
spiceManager.execute(request, request.getCacheKey(), request.getCacheExpiryDuration(), new SpecialOffersRequestListener());
如您所见,一个 SpecialOffersRequestListener
用于从缓存中获取和从网络中获取请求。但是,我不得不采取一些小技巧(请参阅下面的 dataInCache 用法)来处理离线情况,而不用担心用户在缓存中有内容时会出现“无连接”显示:
private final class SpecialOffersRequestListener implements RequestListener<SpecialOffer.List> {
@Override
public void onRequestFailure(SpiceException spiceException) {
if (spiceException instanceof NoNetworkException && dataInCache) {
// Ignore network problems if there is some data in the cache.
return;
}
ActionHelper.showError(getActivity(), "Failed to load special offers.", spiceException);
}
@Override
public void onRequestSuccess(SpecialOffer.List result) {
dataInCache = true;
...
}
}
关于android - 在使用 RoboSpice 执行网络请求之前从缓存中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21735830/