【问题标题】:RXJS update Subject similar to Svelte stores?RXJS 更新主题类似于 Svelte 商店?
【发布时间】:2021-04-15 16:32:04
【问题描述】:

有没有办法用当前值的实例来更新像 Svelte 商店这样的 RXJS 主题? 目前我有:

const materials = someMethodToGetResults();
const tmp = this.activeFilters.value;
tmp.materials = materials;
this.activeFilters.next(tmp);

在我看来这不是很优雅。我总是需要更新整个对象,而我只需要更新属性。我认为 Svelte 解决了这个超级优雅的问题,商店有这样的更新方法:

this.activeFilters.update(current => {
  current.materials = someMethodToGetResults();
  return current;
});

我错过了什么吗? RXJS 的学习曲线相当陡峭。 谢谢。

【问题讨论】:

  • 主题不是商店。它只是提供了一种将值推送给订阅者的机制。您可以使用 RxJS 主题作为创建您自己的“商店”类的解决方案的一部分,该类具有您所寻求的功能。

标签: rxjs svelte subject


【解决方案1】:

没有这样的内置主题,但您可以构建自己的主题

export class StoreSubject extends BehaviorSubject {
   update(updateFn) {
     this.next(updateFn(this.getValue());
   }
}

用法:

const store = new StoreSubject(initialValue);
// .. later:
store.update(val => {
  // do something
  return val
});

【讨论】:

    猜你喜欢
    • 2021-02-27
    • 2020-04-27
    • 1970-01-01
    • 2022-10-17
    • 1970-01-01
    • 2020-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多