如何获取 RxJS Subject 的先前值?

10
在我的项目中,我需要比较我的分页器的 pageSize 值(每页显示的项目数)与之前的值,如果新值更高,则需要从存储中加载数据。但是如果它不比之前的高,我就不想执行任何操作。
例如,在这段代码中:
export class MyComponent {
  paginatorPageSize: BehaviorSubject<number> = new BehaviorSubject<number>(10);
  // ...

  savePageSettings() {
    this.pageService.save().pipe(
      map((result: any) => {
        // ...
      }),
      tap(() => this.anyCode.here()),
      switchMap((result: any) => {
        // ...
      }),
      switchMap(() => {
        const previousPageSize = ??? // <--- here how can I get the prevoius value of paginatorPageSize?

        if (previousPageSize >= this.paginatorPageSize.value) {
          return this.pageService.getAll();
        }

        return of(null)
      })
    ).subscribe();
  }
}

有没有办法获取RxJS Subject / BehaviorSubject或任何类型的subject之前发出的值?

1
你需要使用 pairwise 运算符。 - Roberto Zvjerković
1个回答

25

只需使用pairwise运算符即可。

savePageSettings() {
    this.pageService.save().pipe(
      map((result: any) => {
        // ...
      }),
      tap(() => this.anyCode.here()),
      switchMap((result: any) => {
        // ...
      }),
      pairwise(),
      switchMap(([oldResult, newResult]) => {
        const previousPageSize = oldResult.pageSize;

        if (previousPageSize >= this.paginatorPageSize.value) {
          return this.pageService.getAll();
        }

        return of(null)
      })
    ).subscribe();
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接