从 rxjs 存储中的状态获取最新的 2 个值

Get latest 2 values from status in rxjs store

我需要跟踪商店最新id的变化,所以我需要获取变化前后的值。

 this.store.select(currentSearchSelector).subscribe(search => {
      this.currentSearchId = search.id;
      console.log('current ' + this.currentSearchId);
      // I need to detect the change on this id in the store
    });

什么是关注最新的变化而不丢失以前的变化?

例如:如果 currentSearchID = 21 然后更改为 22 我需要检测此更改。 在我的订阅中,监听器将只持续获取最新的变化。

感谢您的提问!

我认为您可以使用值为 2 的 bufferCount 运算符。

它将创建一个可观察对象,它将仅在缓冲区已满时才发出值,并将值作为数组发出。要查找更多信息,您可以查看 official documentation.

P.S。在您的情况下,缓冲区的大小应为 2。

this.store.select(currentSearchSelector)
    .pipe(bufferCount(2))
    .subscribe(([previousSearch, currentSearch]) => {
       this.currentSearchId = currentSearch.id;
       console.log('current ' + this.currentSearchId);
       console.log('previous ' + previousSearch.id);
    });

此外,还有一个使用 bufferCount 运算符 StackBlitz

的示例

更新

pairwise operator 是 bufferCount 的一个更具体的版本,它只是一起发出最后两项,在这里可能更合适。

无论您选择哪个,您可能还需要将其与 filter operator 结合使用以检查搜索 ID 的变化。