【问题标题】:Reactive programming - observable cache反应式编程 - 可观察缓存
【发布时间】:2020-02-05 14:02:47
【问题描述】:

我对响应式编程和 observables 比较陌生,所以可能有一个明显的解决方案,但我还是不知道如何在 javascript 中使用 observables 制作这个简单的缓存服务

private legalIds: number[]
private personsCache: Person[] // Person has an id as a property

getPersons(ids: number[]) {
  const fromCache = personsCache.filter(p => ids.includes(p.id)) // Get the cached persons
  const newPersons = getPersons(ids.filter(id => legalIds.includes(id) && !fromCache.includes(id))) // Get the ones not already cached, if the ids are allowed

  return fromCache.concat(newPserons)
}

您将如何使用 observables 以脚本方式实现上述 chaching 功能?没有存储数组等的命令式编程。

【问题讨论】:

  • 提供的答案适合您吗?或者你有什么问题吗?写详细的答案是一个相当大的努力,如果理解的话,我希望至少得到反馈

标签: javascript rxjs observable reactive-programming


【解决方案1】:

我实际上不确定您的内部递归 getPersons(..) 调用。但是让我们想象一下它是一个函数,它只返回有关某些 id 的人,并且它是非递归的。

private legalIds$: Subject<number[]> = new Subject();
private personsCache$: Subject<Person[]> = new Subject();

getPersons$(ids: number[]) {
  const fromCache$ = personsCache$.pipe(
    map(personsCache => personsCache.filter(p => ids.includes(p.id))
  );

  const newPersons$ = legalIds$.pipe(
    map(legalIds => getPersons(ids.filter(id => legalIds.includes(id) && !fromCache.includes(id)))
  );

  return combineLatest([fromCache$, newPersons$]).pipe(
    map(([fromCache, newPersons]) => fromCache.concat(newPersons))
  );
}

- 大多数情况下,如果您在同步编程中有/需要递归行为,您可以通过使用扫描在 rx 中解决这个问题,因为它的状态

- 如果我能更多地理解用例/szenario,那么应该可以不要求 getPersons$ 调用。通常,您还可以提供一个使用 ids$ Observable/Subject(给定您的 getPersons 函数)的 Observable(如 public persons$)。

【讨论】:

    猜你喜欢
    • 2018-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-21
    • 2013-05-15
    • 2019-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多