【问题标题】:Rxjs how to cache the result of an observable for a given argument?Rxjs如何缓存给定参数的可观察结果?
【发布时间】:2020-06-26 06:56:18
【问题描述】:

在我的应用程序中,我使用 rxjs,并且我有一个看起来像这样的方法:

query<T extends TableRow>(queryString: string, silent = false): Observable<T[]> {
  return this.sqliteService.dbQuery<T>(queryString).pipe(
    tap(val => {
      if (this.configService.debugMode && !silent) {
        console.log(`\n${queryString}`);
        console.log(val);
      }
    })
  );
}

我的 query 方法内部调用 dbQuery 来查询一个 sqlite 数据库。

另外,query 方法在我的应用程序中被多次调用。所以我想在queryString 相同时全局缓存结果。

换句话说,我希望 query 方法在使用之前已调用的 queryString 参数调用时避免再次调用 dbQuery,方法是返回先前缓存的值。

不确定这是否相关:我的 query 方法存在于 Angular 单例服务中。

【问题讨论】:

    标签: angular typescript rxjs rxjs6 rxjs-observables


    【解决方案1】:

    第一次通过时,将远程值保存到本地缓存属性中,键为查询字符串。

    在后续请求中,返回对应键的现有属性。

    private cache = {};
    
    query<T extends TableRow>(queryString: string, silent = false): Observable<T[]> {
      if (this.cache.hasOwnProperty(queryString)) {
        return of(this.cache[queryString]);
      }
    
      return this.sqliteService.dbQuery<T>(queryString).pipe(
        tap(val => {
          this.cache[queryString] = val;
    
          if (this.configService.debugMode && !silent) {
            console.log(`\n${queryString}`);
            console.log(val);
          }
        })
      );
    }
    

    【讨论】:

    • 感谢@Kurt,但我希望有一些内置的 rxjs
    • Something 必须在函数之外保留值 - 无论是您自己的主题还是对象。一旦 observable 返回,任何存储在函数中的状态或对函数中创建的 observable 的引用都会消失。
    • 另外,随着cache 对象的大小增加,我想知道它最终是否会更有效率
    【解决方案2】:

    我最终得到了以下解决方案:

    private cache: Observable<string>[] = [];
    
    getItem(id: number): Observable<string> {
    
      if (!this.cache[id]) {
        this.cache[id] = this.query<string>(
          `SELECT column FROM table WHERE id = ${id}`
        ).pipe(shareReplay());
      }
    
      return this.cache[id];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-24
      • 1970-01-01
      • 1970-01-01
      • 2019-12-18
      • 2019-05-21
      相关资源
      最近更新 更多