【发布时间】:2019-04-03 22:34:37
【问题描述】:
我正在尝试创建一个GetAndFetch 方法,该方法首先从缓存中返回数据,然后从 Web 服务中获取并返回数据,最后更新缓存。
akavache 中已经存在这样的函数,但是,它检索或存储的数据就像一个 blob。即,如果我对 rss 提要感兴趣,我只能在整个提要级别工作,而不是单个项目。我有兴趣创建一个将项目返回为IObservable<Item> 的版本。这样做的好处是新的Items 可以在service 返回后立即显示,而不是等待所有Itemss。
public IObservable<Item> GetAndFetch(IBlobCache cache, string feedUrl)
{
// The basic idea is to first get the cached objects
IObservable<HashSet<Item>> cacheBlobObject = cache.GetObject<HashSet<Item>>(feedUrl);
// Then call the service
IObservable<Item> fetchObs = service.GetItems(feedUrl);
// Consolidate the cache & the retrieved data and then update cache
IObservable<Item> updateObs = fetchObs
.ToArray()
.MyFilter() // filter out duplicates between retried data and cache
.SelectMany(arg =>
{
return cache.InsertObject(feedUrl, arg)
.SelectMany(__ => Observable.Empty<Item>());
});
// Then make sure cache retrieval, fetching and update is done in order
return cacheBlobObject.SelectMany(x => x.ToObservable())
.Concat(fetchObs)
.Concat(upadteObs);
}
我的方法的问题是Concat(upadteObs) 重新订阅fetchObs 并最终再次调用service.GetItems(feedUrl),这很浪费。
【问题讨论】: