问题描述
我写了一个小服务来缓存返回可观察值的请求。看起来像这样:
export class CacheService {
private readonly cacheMap = new Map<string,Observable<any>>();
public cachify<T>(
cacheKey: string,cacheableFunction: () => Observable<T>
): Observable<T> {
const existingCacheItem = this.cacheMap.has(cacheKey);
if (!existingCacheItem) {
this.cacheMap.set(cacheKey,cacheableFunction().pipe(shareReplay()));
}
return this.cacheMap.get(cacheKey);
}
}
然后在类似这样的组件中使用它:
getNodes(): Observable<Node[]> {
return this.cacheService.cachify('nodes|all',() =>
this.http.get<Knotenpunkt[]>('/api/v1/node')
);
}
getNodeById(id: number): Observable<Node> {
return this.cacheService.cachify(`nodes|${id}`,() =>
this.http.get<Knotenpunkt>('/api/v1/node/' + id)
);
}
现在是问题:开发人员有可能两次使用相同的cacheKey
(目的不同!)。这将是有问题的,因为它将覆盖缓存的内容,从而为使用的函数提供错误的值。有什么办法可以让我控制这一点?
我知道这是一个“开发人员问题”,但是在服务中处理该问题会很高兴。
代码中的问题案例:
this.cacheService.cachify('key-a',functionThatReturnsstring);
// should work,because it's a new key
this.cacheService.cachify('key-b',functionThatReturnsNumber);
// should not work,because it's an already used key and returns a number (instead of a string like the first)
this.cacheService.cachify('key-a',functionThatReturnsNumber);
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)